Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel 5 - Many to Many - Attach versus Save

Tags:

php

save

laravel

I have a many to many relationship between two models, users and roles. Is there a difference between saving a relationship using the save() method and using the attach() method?

$user->roles()->save($role, ['expires' => $expires]); //using save
$user->roles()->attach($roleId, ['expires' => $expires]);// using attach

Are the two equivalent? I personally dont see the difference. Thoughts?

like image 494
alaboudi Avatar asked Mar 02 '16 19:03

alaboudi


People also ask

What is Save () in Laravel?

In short save() method is used both for saving new model, and updating existing one. here you are creating new model or find existing one, setting its properties one by one and finally saves in database, while in create method you are passing array, setting properties in model and persists in database in one shot.

What is difference between create and save in Laravel?

save() method is used both for saving new model, and updating existing one. here you are creating new model or find existing one, setting its properties one by one and finally saves in database.

How do I save multiple records in Laravel eloquent?

Sometimes you might need to save multiple records at once and you can do so by using the "saveMany()" method or the "createMany()" method available to each of the Eloquent model relation. Do note that you need to have "hasMany()" relationship in order to do so.


1 Answers

Here is the snippet of code for the save() method. You'll see that it eventually calls attach().

/**
 * Save a new model and attach it to the parent model.
 *
 * @param  \Illuminate\Database\Eloquent\Model  $model
 * @param  array  $joining
 * @param  bool   $touch
 * @return \Illuminate\Database\Eloquent\Model
 */
public function save(Model $model, array $joining = [], $touch = true)
{
    $model->save(['touch' => false]);
    $this->attach($model->getKey(), $joining, $touch);
    return $model;
}

One big difference is that it also saves the model that you are passing to it. In other words, you can essentially create a new role (or even update the old one) while also attaching it to the user. For example:

// Get the user
$user = User::first();

// Instantiate a new role
$role = new Role($attributes);

// Creates the role / persists it into the database and attaches this role to the user
$user->roles()->save($role, ['expires' => $expires]);
like image 166
Thomas Kim Avatar answered Oct 09 '22 18:10

Thomas Kim