When I use eloquent’s Create() method, and try to pass it a numbered array, instead of a key paired array, it actually inserts into DB, but full of null records into the columns. E.G:
$v = [
0 => "123456789"
1 => "123456789"
2 => "123456789"
3 => "123456789"
];
Model::create($v);
It fills that DB table with: null, null, null, null
Model has the $fillable property well declared, lets say:
protected $fillable = [
'col_name1',
'col_name2',
'col_name3',
'col_name4',
];
Looking into to doc, it seems this create method would expect a well paired name => collumn format. Can anyone confirm?
Is there any way eloquent can address that array position 0 is equal to the first model column/property, and so on?
2
Answers
Not exactly, rather
column_name => value
. You can not pass a numeric array to thecreate
method of a model. What you probably could do is get the column listing of the model and then merge that with the values you have. A bit hacky, but should work:Notes:
Schema::getColumnListing()
returns an array of database columns for the model$v
must be in the correct order for this to workarray_combine()
combines two arrays into an associative arrayThere is a way but I suggest you don’t do that. In practice
$fillable
prop always changes as your app grows and it’s not a good idea to depend on the order of its items.But if for some reason you need it you can go with
getFillable()
to get the attributes and then combine it with values like sowhich would return