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?
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
The model does not have an insert, calling Model::insert results in a call to (the Query Builder) Builder::insert through the __call() magic method which then avoids the Eloquent benefits like setting the timestamps for created_at and updated_at fields.
It also avoids the Mass-assignment protection which Eloquent protects you from inserting unintentional data.
So I would always use create or setting each field separately (if you need to modify the incoming data) and call save() on the model instance.
Insert method :
The insert method accepts an array of column names and values.using this method you can insert data without specify fillable and guarded attribute on the model and here created_at and updated_at values put as NULL value by default.
User::insert(['userName'=>'manish','email'=>'test#gmail.com']);
Create method
The create method also used to insert a new model in a single line. It's instance will return you from that method. before using create() will need to specify fillable or guarded attribute on model its protect against mass-assignment by default and its auto fillable value for create_at and updated_at
User::create(['userName'=>'manish','email'=>'test#gmail.com'])
save()
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.
save() accepts a full Eloquent model instance
create()
while in creating method you are passing an array, setting properties in model and persists in the database in one shot.
create() accepts a plain PHP array
Related
I want to create a new record in my database through the API but i get the error "message": "Array to string conversion (SQL: insert into....) from Postman
API Route:
Route::post('/posts','PostController#store');
The store function in my controller:
public function store(Request $request)
{
$post= new Post;
$post->all = $request->all();
$post->save();
}
First, check your post#all field type. If it a database field - you can set only data of the same type, for example for string type you can set only php string.
If it is not a filed but you want to set all attributes from request to model, you can do it with Model::create($request->all()).
However, before doing so, you will need to specify either a fillable
or guarded attribute on the model, as all Eloquent models protect
against mass-assignment by default.
Source - Mass Assignment
In other words to may define a property in model fillable which will be an array and contains fields that will be mass assignable (in your way - fields from request).
It might be better to use $request->only() and provide only the data you want to take out of the request, which will reduce the possibility of user errors causing you a problem, as $request->all() will include any input data, including the query string.
I am using laravel 5.3 and in my custom model, I have some guarded fields like following.
protected $guarded = ['id', 'tnant_id', 'org_id', 'fac_id', 'slug', 'created_at', 'updated_at', 'deleted_at'];
Now When I try to add record using following.
CUSTOM::create(['tnant_id'=>123]);
It returns me following error.
Field 'tnant_id' doesn't have a default value.
Setting field default value in table will not work because each time I am passing value and it is giving error for all guarded fields.
So how I can add guarded fields value in database? In update query, It is allowing to update but on create it gives error.
You simply can't. Model::create(array $attributes = []) is using method fill(array $attributes = []), which, we may say, filter out all guarded attributes, so they will not be assigned. So in point of creation tnant_id will be null.
I come up with two ways of doing this:
A
create a new model instance
set your attribute
save (persist) it to dabase;
So:
$model = new Model;
$model->tnant_id = 123;
$model->save();
B
This is more likely update than create, but, might be useful for you.
Change your DB schema to allow null values for your attribute or put default value.
create model using Model::create()
set attribute & update.
So:
Assuming you are using migrations, in your migration file use:
Schema::create(..
$table->integer('trant_id')->nullable();
//OR
$table->integer('trant_id')->default(0);
...);
Note: It's hard to say which one is more suitable for you use-case, but I see your attribute is called trant_id, which is some form of relation I guess, so I suggest you to take look at Eloquent's relationship, which might be a better answer.
I have a Course Model that have many fields like this :
course_id
title
description
creator
start_date
end_date
reg_start_date
reg_end_date
picture
lesson_count
cost
status
active
teacher
created_at
updated_at
deleted_at
And I have a Form to edit a specified Model. action attribute of the edit form tag is referenced to course.update route.
In the edit Form,in addition to fields with same names of above Model properties, there are many other form fields that not related to Course Model (and used for manyTomany relations or other operations)
Now in public update method , when I want to use Eloquent update() method , Since the number of irrelevant field names are many, I must to use except() method for incoming request. like this :
public
function update (StoreCourseRequest $request, $id)
{
$data = $request->except(['search_node', '_token', 'start_date_picker', 'end_date_picker', 'reg_start_date_picker', 'reg_end_date_picker', 'orgLevels', 'courseCats','allLessonsTable_length']);
$course = Course::findOrFail($id);
$course->update($data);
$course->org_levels()->sync($request->get('orgLevels'));
$course->course_categories()->sync($request->get('courseCats'));
$result = ['success' => true];
return $result;
}
As you see on usage of $request->except() method, I passed many field names to it to filter only proper attributes for use in $course->update($data);.
Now my Question is that Are there any way that we can get only same name model attributes from a field name?
If I understand your question correctly you are trying to avoid having to use the except() method for incoming requests, correct?
If that is the case, you can just skip it altogether and pass the entire request to the update() method as it will only update matching fields (provided they are listed as "fillable" in the method class). This process is called "mass-assignment".
With Laravel & Eloquent, I'd like to :
Create a model, unless it already exists into the database (like Model::firstOrCreate allows)
At the same time, pass it a few attributes, including some which are not listed in the $fillable array of the model (like Model::forceCreate allows).
But how do I combine the capacities of firstOrCreate and forceCreate? Apparently, Model::forceFirstOrCreate doesn't exist!
Use the unguarded method:
$model = Model::unguarded(function() {
return Model::firstOrCreate($attributes);
});
I have a model (let's call it PageModel) with a hasMany relationship (let's call it rulesList). When I create a new PageModel, I want to default rulesList with at least one empty model. How can I do this in Eloquent?
Code Sample:
// Normal instantiation
$this->rulesList; // Equals NULL
// I can set it manually like so, but is that right?
$this->rulesList = Collection::make([new RulesListModel]);
// NOTE: Doing this does not create an empty model when PageModel is output as JSON
There isn't (to my knowledge) a way to do this within the relationship itself. The reason is that an eloquent model is defined by the database query return values.
You could set up some sort of null row in your database, but I would advise against that.
One way that may work: I think it is possible to create an eloquent model without running a query. I think something like EloquentModel::fill($attributes) would do it. Where $attributes is an array of attributes for your model e.g. array('title' => null, 'description' => null);
You'd have to create this manual model and then add it to your relationship.