Associate() in laravel

20.5k Views Asked by At

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..

2

There are 2 best solutions below

5
CUGreen On

Your Address model would need to have a belongsTo User relationship. eg:

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

Note: You would need to make sure you had a foreign key constraint

eg Migration:

Schema::table('addresses', function (Blueprint $table) {
    $table->unsignedInteger('user_id');

    $table->foreign('user_id')->references('id')->on('users');
});
0
Kenny Horna On

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