I'm trying to create entities using mass-assignment Eloquent feature...
$new = new Contact(Input::all());
$new->save();
The problem's that this way, every field's filled out with an empty string instead of null
values as I expected.
I'm currently developing the system and still some table columns're not defined, that's why using this method, to avoid adding every new field to $fillable
array and to a new Contact(array(...));
...
Also I've around 20 fields in this table, so It'd be a bit ugly to have an array such as
$new = new Contact(array(
'salutation' => Input::get('salutation'),
'first_name' => Input::get('first_name'),
'last_name' => Input::get('last_name'),
'company_id' => Input::get('company_id'),
'city' => ...
...
));
Any tips of how to do this or fix?
Update By now I've sorted out this doing the array_filter in the App::before()
filter.
Update In filter was a bit mess. I end up doing:
public static function allEmptyIdsToNull()
{
$input = Input::all();
$result = preg_grep_keys ( '/_id$/' , $input );
$nulledResults = array_map(function($item) {
if (empty($item))
return null;
return $item;
}, $result);
return array_merge($input, $nulledResults);
}
And in my functions.php.
if ( ! function_exists('preg_grep_keys'))
{
/**
* This function gets does the same as preg_grep but applies the regex
* to the array keys instead to the array values as this last does.
* Returns an array containing only the keys that match the exp.
*
* @author Daniel Klein
*
* @param string $pattern
* @param array $input
* @param integer $flags
* @return array
*/
function preg_grep_keys($pattern, array $input, $flags = 0) {
return array_intersect_key($input, array_flip(preg_grep($pattern, array_keys($input), $flags)));
}
}
By now only working with fields that ends with "_id". This is my biggest problem as if a relationship is not NULL
, the database will throw an error as the foreign key "" cannot be found.
Works perfect. Any comment?
See Question&Answers more detail:
os