Imran Imran - 1 year ago 79
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?

Answer Source

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);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download