major697 major697 - 1 year ago 94
PHP Question

Laravel option only for the admin (permission)

I write a method, that which checks whether the user is an administrator in file UserController.php:

public function create(){
$chackIsAdmin = Auth::user()->permissions;
if ($chackIsAdmin === 1) {
return view('users.adduser');
} else {
return redirect('warehouse');

In table "users" I have column "permissions". Each user is assigned a number 1 or 0. 1 - is admin, 0 is NOT an admin.

I wrote also instruction if, which displays option "Add user" only the user administrator:

@if (Auth::user()->permissions === 1)
<li><a href="{{ url('user/create') }}">Add new user</a></li>

It all works correctly, but I wonder whether in Laravel I can do it in a different way ??
Whether my way is safe?

Answer Source

I think the better way is to write the function on the User model.

class User extends Model 
    public function isAdmin()
        return $this->attributes['permissions'] == 1;

Then it's very easy to use...

return Auth::user()->isAdmin() ? view('users.adduser') : redirect('warehouse');