Search code examples
phplaravellaravel-5eloquent

What's difference between Laravel Model functions "create" and "insert"?


Laravel Model allows two functions for inserting the values to the database table. They are

Create: User::create(['id'=>1,'name'=>'stack']);

Insert: User::insert(['id'=>2,'name'=>'overflow']);

I found they perform similar operations. What's difference between them?


Solution

  • insert() :

    If you using insert() method you can't default created_at and updated_at database column it will be null

    DefaultUser::insert(['username'    =>  $request->username, 'city'  =>  $request->city, 'profile_image' =>  $request->profile_image]);
    

    create() : when we use create method you must define this model in fillable fields

    Add in Your Model

     protected $fillable = ['username','city', 'profile_image'];
    

    Add your Controller

    DefaultUser::create(['username'    =>  $request->username, 'city'  =>  $request->city, 'profile_image' =>  $request->profile_image]);
    

    then we can use create method without **mass assignment error ** basically here , table defined fields are protected in your model

    you should define which model attributes you want to make mass assignable. You may do this using the $fillable property on the model