Svetoslav Dimitrov Svetoslav Dimitrov - 2 months ago 6
PHP Question

Laravel 5. Eloquent relations through several tables and behaviour in foreach

I have the following Models:

Shop_list:

public function shopListItem()
{
return $this->hasMany(Shopping_list_item::class, 'shopping_list_id');
}


Shopping_list_item:

public function shoppingList()
{
return $this->belongsTo(Product::class);
}

public function product()
{
return $this->belongsTo(Product::class);
}


Product:

public function shopListItem()
{
return $this->hasMany(Shopping_list_item::class);
}


When I execute this code:

{{$shoppinglists->shopListItem()->first()}}


I get the following correct result:

{"id":1,"shopping_list_id":13,"product_id":69,"quantity":4,"created_at":"2016-09-05 19:23:35","updated_at":"2016-09-05 19:34:53"}


But if I want to loop and get id:

@foreach($shoppinglists as $sh)
{{$sh->shopListItem()->id}}
@endforeach


Then I get the following error:

Call to a member function shopListItem() on boolean


Question: Why in the loop the object is transformed to a boolean? What is the correct way to loop?

Answer

When you want to access the attributes of the related model, you need to use the object, not the function. Note the lack of parenthesis.

{{$sh->shopListItem->id}}

Since it's a hasMany relationship, shopListItem would be an array that you'll need to iterate through:

@foreach($sh->shopListItem AS $item)
{{ $item->id }} 
@endforeach
Comments