3

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'=>'user@laravel.com',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..

Maik Lowrey
  • 15,957
  • 6
  • 40
  • 79
Jp Arcilla
  • 83
  • 1
  • 1
  • 8
  • Hi! Try adding `$address->save();` afterwards – kravis Apr 09 '18 at 03:00
  • Possible duplicate of [Can't get Laravel associate to work](https://stackoverflow.com/questions/26160661/cant-get-laravel-associate-to-work) – kravis Apr 09 '18 at 03:04

2 Answers2

5

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();
Kenny Horna
  • 13,485
  • 4
  • 44
  • 71
0

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');
});
CUGreen
  • 3,066
  • 2
  • 13
  • 22