Mass assignment technique in Laravel

When you learn about laravel, you probably heard about mass assignment, what does it mean? what exactly is mass assignment? should you care about it?

Mass assignment is a technique for inserting/updating data to a database table, instead of passing data one by one for each fields on database table, with mass assignment you can pass all the data (in array) to the model at once, here's an example.

This is mass assignment:
$user = new User(Input::all());

This is not mass assignment:
$user = new User();
$user->name = 'steve';
$user->email = '';
$user->password = Hash::make('123');

Mass assignment is when you send an array to the model creation, basically setting a bunch of fields on the model in a single go, rather than one by one.

You can add an array called fillable on the model to filter which table fields can be inserted/updated (white list).
protected $fillable = ['name', 'email'];

Or you can also add an array called guarded to protect table fields that cannot be inserted/updated (black list).
protected $guarded = ['password'];

When using mass assignment you need to specify either fillable or guarded array on your models, but not both.

Here's another example of mass assignment
$arr = array(
'name' => 'james',
'email' => '',
'password' => '123',
'address' => 'new york',
'age' => 21

If you still don't understand what mass assignment is, please comment down below, the best way to understand is to try out for your self.

No comments :

Post a Comment

Leave A Comment...