Imran Imran - 18 days ago 7
PHP Question

Attaching Order to User model using Eloquent

So I have two models, a User and an Order (a user has many Orders)

The relationship is set as follows in my models:

User Model

public function orders()
{
return $this->hasMany('App\Order');
}


Order Model

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


I am using the following code to attached the currently logged in User to a Order.

Auth::user()->orders()->attach($order_id);


I believe this is correct but I get this error when executing the code:


Call to undefined method Illuminate\Database\Query\Builder::attach()


Can someone explain what I'm doing wrong?

Answer

The attach method is meant for many-to-many relationships. To associate an order with a user in your scenario, you should be able to save the order model this way:

$order = App\Order::findOrFail($order_id);
Auth::user()->orders()->save($order);
Comments