Reputation: 391
i have two tables "Orders" and "users" where id of Users table is foreign key in "Orders" table. i want to fetch data of "Users" table using "Orders" table.
@foreach($orders as $ord)
<tr>
<td>{{$ord->id}}</td>
<td>{{$ord->productname}}</td>
<td>{{$ord->totalprice}}</td>
<td>{{$ord->quantity}}</td>
<td>{{$ord->users->name}}</td>
<tr>
@endforeach
so that i want name of user using {{$ord->users->name}}
query, but
i got error =
Undefined property: stdClass::$users
Upvotes: 0
Views: 54
Reputation: 3702
In Order Model
public function user()
{
return $this->belongsTo(User::class);
}
and in controller where you pass the value of orders,
$order=Order::with('user')->where(your_condition)->get();
then access the value in blade
@foreach($orders as $ord)
<tr>
<td>{{$ord->id}}</td>
<td>{{$ord->productname}}</td>
<td>{{$ord->totalprice}}</td>
<td>{{$ord->quantity}}</td>
<td>{{$ord->user->name}}</td>
<tr>
@endforeach
Upvotes: 0
Reputation: 14278
If you say that you have a user_id
within your orders
table. Then in your Order
model add this:
public function user()
{
return $this->belongsTo(User::class);
}
And in the view you can use it like so:
{{ $order->user->name }}
Upvotes: 2