Laravel Eloquent Persisting


Example

In addition to reading data with Eloquent, you can also use it to insert or update data with the save() method. If you have created a new model instance then the record will be inserted; otherwise, if you have retrieved a model from the database and set new values, it will be updated.

In this example we create a new User record:

$user = new User();
$user->first_name = 'John';
$user->last_name = 'Doe';
$user->email = 'john.doe@example.com';
$user->password = bcrypt('my_password');
$user->save();

You can also use the create method to populate fields using an array of data:

User::create([
    'first_name'=> 'John',
    'last_name' => 'Doe',
    'email'     => 'john.doe@example.com', 
    'password'  => bcrypt('changeme'),
]);

When using the create method your attributes should be declared in the fillable array within your model:

class User extends Model
{
    protected $fillable = [
         'first_name',
         'last_name',
         'email',
         'password',
    ];
}

Alternatively, if you would like to make all attributes mass assignable, you may define the $guarded property as an empty array:

class User extends Model
{
    /**
    * The attributes that aren't mass assignable.
    *
    * @var array
    */
    protected $guarded = [];
}

But you can also create a record without even changing fillable attribute in your model by using forceCreate method rather than create method

User::forceCreate([
    'first_name'=> 'John',
    'last_name' => 'Doe',
    'email'     => 'john.doe@example.com', 
    'password'  => bcrypt('changeme'),
]);

The following is an example of updating an existing User model by first loading it (by using find), modifying it, and then saving it:

$user = User::find(1);
$user->password = bcrypt('my_new_password');
$user->save();

To accomplish the same feat with a single function call, you may use the update method:

$user->update([
    'password' => bcrypt('my_new_password'),
]);

The create and update methods make working with large sets of data much simpler than having to set each key/value pair individually, as shown in the following examples:

Note the use of only and except when gathering request data. It's important you specify the exact keys you want to allow/disallow to be updated, otherwise it's possible for an attacker to send additional fields with their request and cause unintended updates.

// Updating a user from specific request data
$data = Request::only(['first_name', 'email']);
$user->find(1);
$user->update($data);

// Create a user from specific request data
$data = Request::except(['_token', 'profile_picture', 'profile_name']);
$user->create($data);