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

2.7K

2 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

Ahmad Aziz

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 ☕️

Post Tutorials

Learn trending tutorials for ReactJs, React Native, VueJS, NextJs, Laravel, Tailwind CSS, and Flutter development.
View Tutorials

Code Components

Collection of Tailwind CSS components for everyone to use. Browse all of the components that's right for your web projects
View Components

Welcome to PostSrc V3

PostSrc Dark Logo

You have to login to favorite this