Imran_Developer
Imran_Developer

Reputation: 391

I want to fetch data of foreign key's table using laravel

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

Answers (2)

albus_severus
albus_severus

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

nakov
nakov

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

Related Questions