Laravel - Relationships - Updating Belongs To Relationships
If you would like to assign a child model to a new parent model, you may use the associate
method. In this example, the User
model defines a belongsTo
relationship to the Account
model. This associate
method will set the foreign key on the child model:
use App\Models\Account;
$account = Account::find(10);
$user->account()->associate($account);
$user->save();
To remove a parent model from a child model, you may use the dissociate
method. This method will set the relationship's foreign key to null
:
$user->account()->dissociate();
$user->save();