Problem accessing a One to Many relationship in Laravel

4

My Product model has the following relationship:

public function categoria(){
    return $this->belongsTo('estoque\Categoria');
}

and my model Category has:

public function produtos(){
        return $this->hasMany('estoque\Produto');
}

When trying to access in view :

<td> {{$p->categoria}} <td>

Return me:

{"id":1,"nome":"Cerveja","descricao":"Todas cervejas","ativo":1,"created_at":"2015-10-24 13:53:14","updated_at":"2015-10-24 13:53:14"}

But I need only the category name, so I'm trying to access it like this:

<td> {{$p->categoria->nome}} <td>

But it generates the following error:

Trying to get property of non-object

According to the documentation on the Lavael site, I could use {{$p->categoria->nome}} , but I can not. Any ideas?

    
asked by anonymous 24.10.2015 / 17:04

2 answers

0

You need to set the foreign key in the relation, so it looks like this:

public function categoria(){
    return $this->belongsTo('estoque\Categoria', 'categoria_id');
}

Then just access as an object:

<td> {{$p->categoria->nome}} <td>

I asked SOen: link

    
23.11.2015 / 16:47
1

Rafael, for the return you show me you No You have selected the field related to the relationship, if you used the select function.

The problem is that Laravel 4 can not relate items internally when you do not select them.

So if you're doing a select similar look like this:

User::select('nome', 'email')->with('role')->get();

You should do this (add the relationship key between models):

User::select('nome', 'email', 'role_id')->with('role')->get();

Every time I've had problems like this, that's how I solved it.

    
26.10.2015 / 15:24