Skip to content

Instantly share code, notes, and snippets.

@rmrhz
Created October 12, 2015 16:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rmrhz/7c2802e52e5a79af8c92 to your computer and use it in GitHub Desktop.
Save rmrhz/7c2802e52e5a79af8c92 to your computer and use it in GitHub Desktop.
An impractical use for mass assignments in Laravel.
<?php
class Repository
{
/**
* Mass assignment based on fillable, hidden, and guarded attributes
*
* @param obj $model
* @param arr $insertArray
* @return obj
*/
protected function mapInserts($model, $insertArray)
{
$fields = array_unique(
array_merge($model->getFillable(), $model->getHidden(), $model->getGuarded())
);
foreach($insertArray as $key => $val)
{
if ( in_array($key, $fields) ) {
$model->{$key} = $val;
}
}
return $model;
}
}
@rmrhz
Copy link
Author

rmrhz commented Oct 12, 2015

Example usage

$user = $this->mapInserts(new User, $data)->save();
/* or */
$user $this->mapInserts($this->userModel, $data)->save(); // assuming we've injected the user model

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment