Imran Imran - 7 months ago 38
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.


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?


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);