When use create() the fillable values come null

i have an array with values that i am trying to insert it in the database, but when i use create() the values are inserted as null in database while if i use insert() the values insert correct.

This is the code from the controller

public function store(Request $request)
{
    $request->validate([
        'order_number' => 'required',
        'client' => 'required',
        'products' => 'required',
        'amount' => 'required',
        'description' => 'required',
    ]);
   for($i = 0; $i < count($request->products); $i++)
   {
       $values[] = [
         'order_number' => $request->order_number,
         'client' => $request->client,
         'products' => $request->products[$i],
         'amount' => $request->amount[$i],
         'description' => $request->description
       ];
   }
    Order::create($values);
    return redirect('/')->with('msg', 'Order Saved successfully!');
}

and this is the code from the model

public $timestamps = true;

protected $fillable = [
    'order_number',
    'client',
    'products',
    'amount',
    'description',
];

The names are the same and in the database, any reason why the values come null when i use create() method?

>Solution :

insert() method accepts multiple objects in form of arrays to be created, for example :

DB::table('users')->insert([
  ['email' => 'picard@example.com', 'votes' => 0],
  ['email' => 'janeway@example.com', 'votes' => 0],
]);

But create() method does not accept such structure. You cannot create multiple entries using this method. So in this case you either keep using insert(), either move your create() inside for loop.

Edit : createMany() works only on relationships, and apparently DB manipulation in loops is antipattern. In that case you can do something like this :

$created_at = now();
for($i = 0; $i < count($request->products); $i++)
{
   $values[] = [
     'order_number' => $request->order_number,
     'client' => $request->client,
     'products' => $request->products[$i],
     'amount' => $request->amount[$i],
     'description' => $request->description,
     'created_at' => $created_at,
     'updated_at' => $created_at,
   ];
}

Order::insert($values);

Leave a Reply