Do I need to return the client’s name in the View orders?

Asked

Viewed 81 times

1

I am beginner with the Laravel need to return the name of the client in the View orders, at the moment is only getting the ID

Classes

class Ordem extends Model
{   
    protected $fillable =['id','cliente_id','valor','data','problema',];

    public function produtos()
    {
        return $this->belongsToMany(produto::class, 'ordem_id');
    }
    public function servicos()
    {
        return $this->belongsToMany(servico::class,'ordem_id');
    }
}

class Cliente extends Model
{

    protected $fillable = ['id','nome','cpf','endereco','telefone','email'];

    protected $table = 'clientes';  
    public function ordens()
    {
        return $this->hasMany(ordem::class,'cliente_id');

    }
}

class OrdemController extends Controller
{    
    public function listaordens()
    {
       $list_ordens = Ordem::all();    
       return view('ordem.listaordens',['ordens' => $list_ordens]);
    }
}

View

 @foreach($ordens as $o)
 <tr>
    <td> {{$o->cliente_id}} </td>   

    <td class="text-right"> {{($o->data)}} </td>

    <td class="text-center"> {{$o->problema}} </td>

    <td class="text-right"> {{$o->valor}} </td>

    <td class="text-center">
  • Roni, do the Tour, vote for the answers that help you and the community.

1 answer

0

In the model Ordem add the relationship with the model Cliente as follows:

$this->belongsTo(Cliente::class,'cliente_id', 'id');

Observing: this link has the explanation of how to configure relations

in your class code:

class Ordem extends Model
{   
    protected $fillable =['id','cliente_id','valor','data','problema',];

    public function produtos()
    {
        return $this->belongsToMany(produto::class, 'ordem_id');
    }
    public function servicos()
    {
        return $this->belongsToMany(servico::class,'ordem_id');
    }
    public function cliente()
    {
        return $this->belongsTo(Cliente::class,'cliente_id', 'id');
    }
}

In his controller make a forward loading of the interface:

$list_ordens = Ordem::with('cliente')->get();

in your class controller:

class OrdemController extends Controller
{    
    public function listaordens()
    {
       $list_ordens = Ordem::with('cliente')->get();    
       return view('ordem.listaordens',['ordens' => $list_ordens]);
    }
}

and finally in View

@foreach($ordens as $o)
 <tr>
    <td> {{$o->cliente_id}} </td> 
    <td> {{$o->cliente->nome}} </td> 
    <td class="text-right"> {{($o->data)}} </td>
    <td class="text-center"> {{$o->problema}} </td>
    <td class="text-right"> {{$o->valor}} </td>
    <td class="text-center"> 

That is, you need to configure the return relation, as it was configured only Client for Order.

Behold:

  • Thank you, that’s right returned the name right

  • @Ronicardoso if useful tick as answer of your query

Browser other questions tagged

You are not signed in. Login or sign up in order to post.