Home / Snippets / How to Associate and Dissociate Relationship in Laravel
How to Associate and Dissociate Relationship in Laravel cover

How to Associate and Dissociate Relationship in Laravel

3.2K

3 years ago

0 comments

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

notion avatar

Alaz

Week-end developer currently experimenting with web, mobile, and all things programming.

Topics:

Frontend

Resource

Average

Average

Support Us

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

Welcome to PostSrc V3

PostSrc Dark Logo

You have to login to favorite this