SET RELATIONSHIPS WITH THE ASSOCIATE METHOD

Jun 19, 2024 Copy Link

In a many-to-many relationship, use the attach method to link a child model to its parent. In contrast, for a one-to-one relationship, use the associate method:

 

use App\Models\Post;

$post = Post::findOrFail(6);

// Associate the post with the user (not yet saved to the database)
$post->user()->associate(auth()->user());

// Save the post along with the relationship
$post->save();

 

The reverse of the previous method is `disassociate`, which does not remove the user's post but sets the `user_id` to NULL.

Share via

Mahmoud Ramadan

Mahmoud Ramadan

Mahmoud is the creator of Digging Code and a contributor to Laravel since 2020.

Newly published

  • How to Enable Relationship Autoloading in Versions Before v12.8

    How to Enable Relationship Autoloading in Versions Before v12.8

    PREMIUM

  • Get your environment ready to welcome Laravel v12

    Get your environment ready to welcome Laravel v12

    PREMIUM

  • How to generate Arabic PDF using TCPDF

    How to generate Arabic PDF using TCPDF

    FREE