I have a multi-dimensional array coming from post request. It looks like this: $request['bags'][1]['fruits']
. Sometimes, this value doesn't exist so it returns Undefined Index error.
$model->fruits = $request['bags'][1]['fruits'];
If I use an isset guard in my controller, it works:
$model->fruits = isset($request['bags'][1]['fruits'];) ? $request['bags'][1]['fruits'] : '';
$model->save();
Now, I wanted to wrap this in a function, so that I can use something like nullable($fruits)
to make this work.
Now, I tried to wrap this inside a helper method; so I created Helper.php and added this method inside:
function nullable($value) {
return (isset($value)) ? $value : '';
}
But in my controller, when I call nullable()
, it throws Undefined Index error.
nullable($request['bags'][1]['fruits']); // Undefined Index
isset($request['bags'][1]['fruits']) ? $request['bags'][1]['fruits'] : ''; // works