'whats the difference between fillable and guard in laravel?
I am newbie in Laravel and want to understand this with example. what are main difference between fillable and guard in laravel? How those are differentiated? Please share one basic example.
Solution 1:[1]
Example 1
protected $fillable = ['name', 'email'];
It means we want to insert only name,and email colmn values
Example 2
protected $guarded = ['name', 'email'];
It means we want to ignore only name & email we don't want to insert values of name & email colmn
Example 3
protected $guarded = [];
We want to insert all columns values
Solution 2:[2]
First as a newbie refer the documentation on laravel site. I suppose you are asking about fillable vs guarded.
Fillable is ready for mass assignments i.e. you can use fill() with array of value sets instead of one-one assignments. Below name and email are fillable.
class User extends Eloquent{
public $timestamps = false;
protected $fillable = ['name', 'email'];
}
....
$user = User::create($request->all);
Guarded is just opposite of fillable.
keep in mind there is one more "hidden" which means its not available for json parsing. so if you use
return User::all();
the returned json will skip all fields mentioned in hidden. Also the hidden doesn't explicitly means guarded.
Solution 3:[3]
In Laravel, $fillable attribute is used to specify those fields which are to be mass assignable. $guarded attribute is used to specify those fields which are to be made non mass assignable.
$fillable serves as a "white list" of attributes that should be mass assignable and $guarded acts just the opposite of it as a "black list" of attributes that should not be mass assignable.
If we want to block all the fields from being mass-assigned, we can use:
protected $guarded = ['*'];
If we want to make all the fields mass assignable, we can use:
protected $guarded [];
If we want to make a particular field mass assignable, we can use:
protected $fillable = ['fieldName'];
Lastly, if we want to block a particular field from being mass assignable, we can use:
protected $guarded = ['fieldName'];
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Kai - Kazuya Ito |
| Solution 2 | iSensical |
| Solution 3 | YDF |
