DEV3 Technologies home

DEV3 Developer Forum

What does MassAssignmentException mean and how should I use fillable and guarded?

Laravel helpSolved0 views
dev3 ·

I call User::create($request->all()) and get "Add [name] to fillable property to allow mass assignment". I was tempted to set $guarded = [] to make it go away. Is that safe?

#laravel#eloquent#security

0

1 reply

dev3 · Accepted answer

Mass assignment protection stops a request from setting columns you never meant to expose, such as is_admin, role or balance. Eloquent only fills attributes listed in $fillable (allow list) or not listed in $guarded (deny list).

Preferred: explicit allow list

class User extends Authenticatable
{
    protected $fillable = ['name', 'email', 'password'];
}

Even better: validate and use only validated data

$user = User::create($request->validated());

validated() returns only the keys covered by your rules, so extra fields in the request are dropped before Eloquent even sees them. Never pass $request->all() to create() or update().

Why $guarded = [] is risky

It disables protection entirely. If someone posts is_admin=1 and your code does User::create($request->all()), they are an admin. Even if today's form is safe, a later refactor is not.

Alternatives

  • $user->forceFill([...])->save() bypasses the guard intentionally, for internal code with trusted data.
  • Set sensitive columns explicitly: $user->role = 'editor';.
  • In development Model::shouldBeStrict() (in AppServiceProvider) turns on strict mode: lazy loading, accessing missing attributes and silently discarded fills all throw, which helps you find mistakes.

Pitfalls

  • A column missing from $fillable fails silently in fill()/create() unless strict mode is on, which looks like a "field not saving" bug.
  • Pivot attributes and JSON sub-keys follow the same rules; $fillable = ['options->theme'] is allowed for JSON paths.
  • Do not guard only id; list fields explicitly.
0

Your reply

Every post is reviewed by DEV3 before it appears. Usually reviewed within 24 hours.

Markdown supported. Use ``` for code blocks. Images are not allowed.