I’m trying to create shopping cart page. From controller I’m getting an array of order items.
Order item has foreign key "meal_id" – relationship with table meals. I need to access to connected meal object, to display information. How should I do it correctly? I tried to include php key inside blade template:
@foreach($order_items as $order_item)
...
@php
$meal = AppModelsMeal::where('id', '=', $order_item->meal_id)->get();
@endphp
...
@endforeach
But it doesn’t work. Of course I can send two different arrays of order_items and meals and hope, that sequence will be equal…
Or I can somehow send one array with joint tables.
But isn’t there more simple way to do this?
2
Answers
You need to define a relationship between the models so you’ll have access to it via the Eloquent ORM and you will be able to do something like that in your blade template for example:
You can read more about Laravel relationships and how to set each type of relationship here
you can’t intract with database inside view files , this is neither clean code , nor usefull, and it is cause a problem called N+1 problem ,
the solution is to create a relationship inside the model class, you can find more about relationships at laravel.com,
anyway here is an examlpe :
first thing create a method inside the
Order
model namedmeals
, then you need to select which relation you should use , in your case the relation is has many , since Meal has many order items , so inside the meal method use like this:return $this->belongsTo(Order::class)
.for more examples I realy recommend you to see Eloquent Relationships on laravel.com
they have a great docs to simplify these things,
after creating the relationship and before passing the
$order_items
to the view, you should load the relation , somthing like this :Order::with('meal')->get()
or if you already have an instanse you can use$orders->load('meal')
, ther is several ways how to call a relationship , but however you do it , try to do it outside the view section or any loops insid blade