Laravel Model Fillable vs Guarded Attributes
Fillable and Guarded arrays works the same but are the opposite of each other and this article will discuss exactly what is fillable and guarded.
There are three methods to save, update records in Laravel.
- Raw Query
- Creating a New object of the Model
- Using Eloquent Method Create
For example we have a table employees having two fields employee_name and employee_email.
In order to save a record to the table wo do,
public function store(Request $request) { $employee = new Employee(); $employee -> employee_name = $request -> name; $employee -> employee_email = $request -> email; $employee -> save(); }
This will work fine but will be more difficult if the table will have more fields like 10 or more, so Laravel come with very handy method called create to overcome this.
public function store(Request $request) { $employee = Employee::create($request->all()); }
But this will not work and will give error of MassAssignmentException because Laravel want to send a Token named as _token as hidden field which comes from the request automatically.
To avoid the error we specify the fields in a fillable array in model like
<?php namespace App; use Illuminate\Database\Eloquent\Model; class Employee extends model { protected $fillable = ['employee_name', 'employee_email']; }
The fillable array will insure to only process those will be present in the fillable array, this increasing the security of your application. The Primary key Id and timestamp will be handled automatically so you don’t need to include the id and timestamp in the fillable array.
Now if you will have more fields then there is another way to handle the situation and is the guarded field.
<?php namespace App; use Illuminate\Database\Eloquent\Model; class Employee extends model { protected $guarded = ['id']; }
guarded array is the opposite of fillable array and we should only guard the id. Timestamp are automatically handled and you don’t need to guard that, and if you want toguard more fields you can also do that.