5
votes

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?

2

2 Answers

6
votes

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.

5
votes

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.