laravel|
Mass Assignment Vulnerabilities can allow users to modify data that shouldn’t normally be modifiable. Imagine a user being able to set their administrator status, grant themselves additional permissions, or change the password of another user. This could result in a dangerous situation for your application! Fortunately, most modern frameworks give you the ability to protect against this kind of attack. With Laravel this is handled by providing one of two properties on your models; $fillable or $guarded.
Using Fillable or Guarded is fairly straightforward; provide a protected property on your model and define a list of attributes. With $fillable you’ll provide a list of attributes that are allowed to be mass assigned. With $guarded you’ll provide a list of attributes that are blocked from being mass assigned. Let’s imagine we have a User model that starts out with the following attributes:
emailfirst_namesurnamephone_numberis_adminpasswordWe want users to be able to update the email, first_name, surname, and phone_number. However, we don’t want them to mass assign the attributes is_admin or password.
Protecting this model with $fillable would look something like:
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
protected $fillable = [
'email',
'first_name',
'surname',
'phone_number',
];
}
Protecting this model with $guarded would look something like:
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
protected $guarded = [
'is_admin',
'password'
];
}
$fillableAlthough these 2 approaches appear similar, there are a few reasons to prefer $fillable.
At Roave we generally choose explicitness over implicitness whenever given the choice. Particularly with legacy codebases, using explicit, descriptive names and code constructs can greatly increase your app’s readability and your developer’s understanding.
Using $fillable automatically protects new attributes on the model that should not be mass assigned. If you use $guarded new attributes can be mass assigned unless you update the list of attributes. If you forget to add an attribute to $fillable data may not be populated. If you forget to add an attribute to $guarded you may be susceptible to mass assignment exploitation.
When using $guarded, it is possible in certain circumstances that the Model may make a database query. This could cause problems in tests where a database connection may not be available.
Regardless of which method you choose, make sure you’re using Laravel’s built-in protections against mass assignment vulnerability! Have questions or comments about Laravel or software-development? Come say hi in our Discord!