Posts Learn Components Snippets Categories Tags Tools About
/

How to Associate and Dissociate Relationship in Laravel

Learn how to associate and dissociate a relationship in Laravel the easy way. Get to know how to specify a model for the belongsTo relation and the inverse.

Created on Sep 16, 2021

3084 views

To associate and dissociate a relationship model in Laravel you have to make sure that the corresponding model belongs to something. What this means is that the modal instance itself can be associated and dissociated based on how the relationship has been defined.

Define belongsTo relationship


Do imagine a "Post" model that belongs to "User" model. This can either be a "one to one" or "one to many" definition.
  • User => has one => Post
  • User => has many => Post
The inverse relation from the Post model will be the "belongsTo" definition.
  • Post => belongs to => User

How to associate a Model


To associate a model you can call the "associate" method on the relationship.
<?php

$firstUser = User::first();

Post::first()->user()->associate($firstUser)->save();

How to dissociate a Model


To dissociate a model you can call the "dissociate" method on the relationship.
<?php

$firstUser = User::first();

Post::first()->user()->dissociate($firstUser)->save();
Do note that you have to call the "save()" method in order for the code to be executed.

Other Reads

If you like our tutorial, do make sure to support us by being our Patreon or buy us some coffee ☕️

)