PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Tuesday, March 1, 2022

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

 March 01, 2022     eloquent, laravel, laravel-5, php     No comments   

Issue

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



Answered By - Hitesh
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing