Note that there are some explanatory texts on larger screens.

plurals
  1. POEmpty string instead of null values Eloquent
    text
    copied!<p>I'm trying to create entities using mass-assignment Eloquent feature...</p> <pre><code>$new = new Contact(Input::all()); $new-&gt;save(); </code></pre> <p>The problem's that this way, every field's filled out with an empty string instead of <code>null</code> values as I expected.</p> <p>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 <code>$fillable</code> array and to a <code>new Contact(array(...));</code>...</p> <p>Also I've around 20 fields in this table, so It'd be a bit ugly to have an array such as</p> <pre><code>$new = new Contact(array( 'salutation' =&gt; Input::get('salutation'), 'first_name' =&gt; Input::get('first_name'), 'last_name' =&gt; Input::get('last_name'), 'company_id' =&gt; Input::get('company_id'), 'city' =&gt; ... ... )); </code></pre> <p>Any tips of how to do this or fix?</p> <p><strong>Update</strong> By now I've sorted out this doing the array_filter in the <code>App::before()</code> filter.</p> <p><strong>Update</strong> In filter was a bit mess. I end up doing:</p> <pre><code>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); } </code></pre> <p>And in my functions.php.</p> <pre><code>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))); } } </code></pre> <p>By now only working with fields that ends with "_id". This is my biggest problem as if a relationship is not <code>NULL</code>, the database will throw an error as the foreign key "" cannot be found.</p> <p>Works perfect. Any comment?</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload