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.