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());
$user->save();

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

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' => 'james@yahoo.com',
                'password' => '123',
                'address' => 'new york',
                'age' => 21
	);
User::create($arr);

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.

3 comments

Class 9 Assignment 2021 has been published with the answer for 1st week Bangla, Science and Bangladesh and Class 9 Assignment 2021

Class 9 Assignment 2021 has published on www.topstories247.com. All students can download PDF Assignment question and Syllabus from the website. Answer of Assignment is also available.class 9 assignment 2021

I admire this article for the well-researched content and excellent wording. I got so involved in this material that I couldn’t stop reading. I am impressed with your work and skill. Thank you so much. Class 8 Assignment Answer


EmoticonEmoticon