Laravel Mass Assignment for Admins
Asked Answered
A

2

5

I have an app with a Users table with columns: id|name|email|is_admin. I want admins to be able to set other users as admins.

In models/User.php I prevent mass-assignment with:

protected $fillable = ['name', 'email'];

Laravel 4 Role Based Mass Assignment concludes that Laravel has no such feature.

My question is, what is a viable work-around? How can I allow only admins to update the column 'is_admin' in my database?

Amboina answered 26/9, 2014 at 20:49 Comment(0)
D
6

Extend your User model to create an admin-only version without the mass-assignment protection.

In the new class, override the $fillable property:

class UnprotectedUser extends User
{
    protected $fillable = [<all fields>];
}

Then use the new model in your admin-specific code:

$user = UnprotectedUser::create($arrayOfAllFields);

Be sure to use the original class in as many places as possible so that you can continue to take advantage of the mass-assignment protection.

Delude answered 26/9, 2014 at 22:4 Comment(1)
This is a great answer because it allows you to continue using the built in ::create() functionality for mass-assignment.Amboina
O
5

Actually, the following code:

protected $fillable = ['name', 'email'];

will prevent from Mass-Assignment which means that, someone can't use something like this:

User::create(['name' => 'xxx', 'email' =>'[email protected]', 'is_admin' => 1]);

In this case, the is_admin field won't be updated but it's still possible do the same thing using something like this (it's not Mass Assignment):

$user = User::find($id); // Or $user = new User; (when creating a new user);
$user->name = 'xxx';
$user->email = '[email protected]';
$user->is_admin = 1;
$user->save();

So there will be no problem to update the User like this way.

Outrage answered 26/9, 2014 at 22:36 Comment(1)
I ultimately used this answer because it allowed more flexibility in the model. E.g. On update() I wanted to only modify the users password if a new one was passed in.Amboina

© 2022 - 2024 — McMap. All rights reserved.