Problem accessing a One to Many interface in Laravel

Asked

Viewed 545 times

5

My Product model has the following relationship:

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

and my Category model has:

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

When trying to access the view:

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

Call me back :

{"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 only need the category name, so I’m trying to access it like this:

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

But generates the following error:

Trying to get property of non-object

According to the documentation on the website of Lavael, I could use {{$p->categoria->nome}}, but I can’t. Any idea?

  • Rafael, how is your model Categoria? The inverse ratio has been defined hasOne ?

  • I edited the question.

  • 1

    Try to use as an array <td> {{$p->categoria['nome']}} <td>

  • Yes this works, but I had seen some examples on the internet and they accessed as object and not array.

  • Quite strange Rafael, I couldn’t reproduce your problem here. Try updating with a composer update, eeu code is versioned somewhere?

  • It is not only on my pc, and I realized the composer update.

  • I’ve seen that example somewhere ...

  • Do you have any product related to the category?

  • In this example a product belongs to a category, but I don’t know why it returns an array

Show 4 more comments

2 answers

1

Rafael, by the return you show me you Not Selected the field related to the relationship, if you used the function select.

The problem is that Laravel 4 can’t relate items internally when you don’t select them.

So if you’re doing a select similar to that:

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, this is how I solved.

0


You need to set the foreign key in the relationship, so it stays like this:

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

So just access as an object:

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

I asked on the Soen: link

Browser other questions tagged

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