Do I need to return the customer name in the View orders?

1

I am new to Laravel and need to return the client name in the View orders, currently it is only taking 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">
    
asked by anonymous 25.11.2018 / 00:18

1 answer

0

No model Ordem add the relation with model Cliente as follows:

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

-muitos-laravel / 152108 # 152108 "> this link has the explanation of how to configure relationships

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');
    }
}

At your controller load the relationship in advance:

$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 lastly on 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 set the relationship of the back, as it was just configured Client to Order .

See:

25.11.2018 / 00:39