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..
Your Address model would need to have a belongsTo User relationship. eg:
Note: You would need to make sure you had a foreign key constraint
eg Migration: