notANerdDev notANerdDev - 7 months ago 34
PHP Question

Creating a Model::create dynamically using call_user_func_array gives an error on Laravel 5.2

I have the following code to create an entry in the database:

$element_names_array = explode(',', $request->input('element_names'));
foreach ($element_names_array as $element)
$data[$element] = $request->input($element);
$model = '\\App\\' . $request->input('connected_model');
return call_user_func_array($model . '::create', $data);

An array is created and passed onto the call_user_func_array function, which triggers the
method passing the array as an argument.

But, for some reason, right after the
the array type gets converted to string type.

I'm getting this error and error log:

Type error: Argument 1 passed to Illuminate\Database\Eloquent\Model::create() must be of the type array, string given

Error log

in Model.php line 570
at Model::create('R200500002', 'MALSKDJSNAM123123')
at call_user_func_array('\App\RepairOrder::create', array('ro_number' => 'R200500002', 'vin_number' => 'MALSKDJSNAM123123')) in GdmsBotTask.php line 26

As you can notice, an array is passed to the call_user_func_array... but it gets converted to string. What's going on?


call_user_func_array converts the array into individual parameters.

To fix, use call_user_func or wrap $data in a parent array:

return call_user_func($model . '::create', $data)
return call_user_func_array($model . '::create', [$data])

As a side note, unless this code is only callable by highly trusted authenticated users, then you have a huge security problem