Associate() in laravel

Jp Arcilla picture Jp Arcilla · Apr 9, 2018 · Viewed 8.5k times · Source

I have 2 models, a User and an Address. I am still experimenting on associate() since I read it in https://laravel.com/docs/5.6/eloquent-relationships#updating-belongs-to-relationships but I'm having some trouble with implementing it and sadly my video tutorial doesn't cover the associate() function.

class User extends Authenticatable
      public function address() {
      return $this->hasOne('App\Address');
}

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

// --web.php--

Route::get('/sample',function(){
$user = User::create(['name'=>'user 1','email'=>'[email protected]',password='']);
$address = Address::create(['name'=>'sample address of user 1']);

$address->user()->associate($user);

});

Everything was saved, but I was expecting that user_id of the address would be 1. Instead, user_id of the address was set to NULL. Isn't associate() suppose to link a specific 'belongsTo' model to its parent by automatically assigning the foreign key equal to the parent's ID? BTW im very new to PHP and Laravel so yeah..

Answer

Kenny Horna picture Kenny Horna · Apr 9, 2018

You still need to save the object to store the value.

As the documentation says:

Belongs To Relationships

When updating a belongsTo relationship, you may use the associate method. This method will set the foreign key on the child model:

$account = App\Account::find(10);

$user->account()->associate($account);

$user->save();

So, as you can see, after associate it:

$address->user()->associate($user);

you need to save it:

$address->save();