Lord Jesus
Lord Jesus

Reputation: 170

laravel- how do I retrieve name through the master table?

I have three models that is:

User
Order
UserInfo

In User Model:

  /* Attribute to set primary user */
    protected $primaryKey = 'user_id';

     public function userInfo()
        {
            return $this->hasOne('App\Models\Users\UserInfo', 'user_id');
        }

      public function orders()
        {

            return $this->hasMany('App\Models\Orders\Order', 'user_id');
        }

In Orders model:

// Set table
protected $table = 'orders';

// Set timestamps
public $timestamps = true;

// Set primary key
protected $primaryKey = 'order_id';

// Set mass assignable columns
protected $fillable = [];

// Manys orders can belong to one user

public function user()
{
    return $this->belongsTo('App\Models\Users\User', 'user_id');
}

In UserInfo model:

 // Set table
    protected $table = 'user_infos';

    // Set timestamps
    public $timestamps = true;

    // Set primary key
    protected $primaryKey = 'user_id';

    // Set mass assignable columns
    protected $fillable = [];




    /**
     * Get the user info associated with the user.
     */

    public function user()
    {

        return $this->belongsTo('App\Models\Users\User', 'user_id');
    }

Each of their table has a common column called user_id where I will access through the Order model with the user id to match it with User model and retrieve the name from User Info.

I tried to retrieve it with Order::all()->user->userInfo->name->get() but it says Exception with message 'Property [user] does not exist on this collection instance.'

What did I do wrong?

Upvotes: 1

Views: 55

Answers (1)

Lijesh Shakya
Lijesh Shakya

Reputation: 2540

You are trying to retrieve the user relation into the collection of orders.

It can be achieved from model instance instead of the collection like:

$user = Order::first()->user;

If you want to display all users of the orders, you can loop through the orders and retrieve user:

foreach($orders as $order){
    $user = $order->user;
}

Upvotes: 1

Related Questions