The difference between laravel insert, save, update, create

Posted May 27, 20202 min read

insert:When inserting data, you need to maintain the created \ _at and updated \ _at fields

To create a new record in the database, just create a new model instance, set properties on the model, and then call the save method:

<? php

namespace App \ Http \ Controllers;

use App \ Flight;
use Illuminate \ Http \ Request;
use App \ Http \ Controllers \ Controller;

class FlightController extends Controller
{
   /**
     * Create a new flight instance.
     *
     * @param Request $request
     * @return Response
     * /
    public function store(Request $request)
    {
        //Verification request ...

        $flight = new Flight;

        $flight-> name = $request-> name;

        $flight-> save();
    }
}

save:Whether inserted or updated, it will be automatically maintained without manual operation

Use the save method. Similarly, the updated \ _at timestamp will be automatically updated, so we don't need to set its value manually:

$flight = App \ Flight ::find(1);

$flight-> name = 'New Flight Name';

$flight-> save();

update:update operation, automatically maintain the updated \ _at field

The save method can also be used to update models that already exist in the database. To update the model, you must first retrieve the model, then set the attributes to be updated, and then call the save method. Similarly, the updated \ _at timestamp will be automatically updated, so we don't need to set its value manually:

$flight = App \ Flight ::find(1);

$flight-> name = 'New Flight Name';

$flight-> save();

The update method needs to pass in an array of key-value pairs representing the values of the fields of the field to be updated.

When performing batch updates via Eloquent, saved and updated model events will not be triggered by the updated model. This is because no model will be retrieved when performing batch updates.

create:Automatically maintain the created \ _at and updated \ _at fields

You can also use the create method to save the new model, and then the model instance inserted into the database will be returned from the method. However, before that, you need to specify the fillable or guarded attributes on your model, because all Eloquent models cannot be assigned in batches by default.

$flight = App \ Flight ::create(['name' => 'Flight 10']);