Skip to content

Instantly share code, notes, and snippets.

@rmrhz
Created Oct 12, 2015
Embed
What would you like to do?
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