skip to Main Content

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


  1. Looking into to doc, it seems this create method would expect a name => column format.

    Not exactly, rather column_name => value. You can not pass a numeric array to the create 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:

    use IlluminateSupportFacadesSchema;
    
    Model::create(array_combine(Schema::getColumnListing(
        app(Model::class)->getTable()
    ), $v));
    

    Notes:

    Login or Signup to reply.
  2. There 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 so

    array_combine(
      (new Model)->getFillable(), 
      $v
    )
    

    which would return

    [
      'col_name1' => "123456789",
      'col_name2' => "123456789",
      'col_name3' => "123456789",
      'col_name4' => "123456789",
    ]
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search