Interview answer
Mass assignment allows multiple model attributes to be populated from an array.
$user->fill($request->all());
This can be dangerous because users could submit fields they shouldn't control.
Laravel provides $fillable and $guarded.
Code
class User extends Model
{
protected $fillable = [
'name',
'email',
];
}
Then:
User::create([
'name' => 'John',
'email' => 'john@example.com',
]);
I prefer explicitly defining $fillable for important application models.
Scenario
If the database contains:
name
email
is_admin
and I blindly do:
User::create($request->all());
a malicious request might attempt:
{
"name": "John",
"email": "john@example.com",
"is_admin": true
}
Mass-assignment protection helps prevent this class of vulnerability.
0 comments:
Post a Comment
Thanks