Laravel bulk assignment for admins

I have an app with the 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 Bulk Assignment concludes that Laravel does not have such a feature.

My question is, what is viable work ? How do I only allow admins to update the "is_admin" column in my database?

+3


source to share


2 answers


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

In the new class, override the property $fillable

:

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 as often as possible so that you can continue to use mass assignment protection.

+5


source


Actually, the following code:

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

      

will prevent Mass-Assignment

, which means someone can't use something like this:

User::create(['name' => 'xxx', 'email' =>'x@mail.com', 'is_admin' => 1]);

      



In this case, the field is_admin

won't update, but it is still possible to do the same using something like this (it is not Mass Assignment

):

$user = User::find($id); // Or $user = new User; (when creating a new user);
$user->name = 'xxx';
$user->email = 'x@mail.com';
$user->is_admin = 1;
$user->save();

      

So there is no need to update User

this way.

+3


source







All Articles