ATTACH VS ASSOCIATE

Jun 19, 2024 Copy Link

We know that to assign a child model to a parent model in many-to-many relationship we use the attach method, and to do so in one-to-one relationship, you may follow the coming traditional way:

 

use App\Models\Post;

Post::create([
    'title'   => 'Welcome to the traditional Way',
    'body'    => 'Trying to attach two models in a traditional way.',
    'user_id' => auth()->id()
]);

 

But, do you know that Laravel ships in another nice way by using the associate method:

 

use App\Models\Post;

$post = new Post;

$post->title = 'Welcome to `associate` method';
$post->body  = 'Trying to attach two model in a different way.';

$post->user()->associate(auth()->user());

$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.

Most recent

  • How to generate Arabic PDF using TCPDF

    How to generate Arabic PDF using...

    FREE

  • What is SQL Injection

    What is SQL Injection

    FREE

  • Leveraging virtual generated columns in MySQL using Laravel

    Leveraging virtual generated col...

    FREE