HeartOfprogrammer
HeartOfprogrammer

Reputation: 537

Laravel: How to check if user is admin?

I want to make the user an administrator who at the entrance to the site conditions are checked == user login , if so then give the right to remove or edit product. This is my code so far:

@if(Auth::check())
   <p><a href="#" class="btn btn-success" role="button">Edite</a> <a href="#" class="btn btn-danger" role="button">Remove</a></p>
@endif

How equate Auth::check() with my login?

Upvotes: 9

Views: 82065

Answers (13)

RB Projects
RB Projects

Reputation: 768

1.First step - create database column for user type

First, you need to add to your users table a column for the user type - let's name it "user_type_id" (I prefer to work with IDs because it is faster and well-organized)

In migrations folder find your user table migration file and in the up() method you should have something like this:

Schema::create('users', function (Blueprint $table) {
        $table->id();
        $table->string('name');
        $table->string('email')->unique();
        $table->string('password');
        $table->integer('user_type_id')->default(config('app.default_admin_type_id'));
        $table->rememberToken();
        $table->timestamps();
    });

This line is important to be added: (the user_type_id)

$table->integer('user_type_id')->default(config('app.default_admin_type_id'));

In the folder and file config/app.php I created a constant named default_admin_type_id equal to -1. (you can set it to whatever number you want) I use this constant to update the value into one place and then check for it wherever I want.

'default_admin_type_id' => -1,

2.Second - edit AuthServiceProvider.php

Go to the file /app/Http/Providers and open AuthServiceProvider.php file and edit the boot() method like this:

public function boot()
    {
        Gate::define("Admin",function(User $user){
            
            if($user->user_type_id == config('app.default_admin_type_id')){
               return true;
            }
            return false; 
        });

        $this->registerPolicies(); 
    }

The idea here is that you create (define) a gate with the name "Admin" and you check if the user_type_id is equal to the default_admi_type_id stored in the app.php config files.


3.Use the "Admin" gate in classes

You can check if a user is of the desired type like this:

public function delete()
{
    if (Gate::allows('Admin')) {
        dd('Admin allowed');
    } else {
        dd('You are not Admin');
    }
}

4.Use the "Admin" gate in blade views

You can check if a user is of the desired type like this:

    @can('Admin')
<p><a href="#" class="btn btn-success" role="button">Edite</a> <a href="#" class="btn btn-danger" role="button">Remove</a></p>
    @endcan

That's all!

Cheers, Hope to help other scenarios as well.

Upvotes: 0

toolnin
toolnin

Reputation: 144

For Laravel 7 or 8 (this is an update to devnull's answer which I think is the best approach)

Inside your project folder create the following models:

$ php artisan make:model Role -m
$ php artisan make:model role_user -m 

This will generate the files:

  • create_roles_table.php
  • create_role_users_table.php
  • Models/Role.php
  • Models/role_user.php

Add the following fields to the create_roles_table.php Schema:

$table->id();
$table->string('name');
$table->timestamps();

Add the following fields and foreign key relationships to the create_role_users_table.php Schema and ALSO change the table name by removing the letter 's' added by Laravel on 'role_users' to be 'role_user':

public function up()
{
    Schema::create('role_user', function (Blueprint $table) {
        // having $table->id(); here is optional
        $table->bigInteger('user_id')->unsigned();
        $table->bigInteger('role_id')->unsigned();
        $table->foreign('user_id')->references('id')->on('users');
        $table->foreign('role_id')->references('id')->on('roles');
    });
}

Also rename 'role_users' to 'role_user' in the down() method Schema:

Schema::dropIfExists('role_user');

Run your migrations:

$ php artisan migrate

Add some data to your roles table depending on your needs, for example:

id: 1 | name: "Admin"
id: 2 | name: "Moderator"
id: 3 | name: "Basic"

Go to the User Model and create the function that handles the relationship between Role and User:

public function roles() {
   return $this->belongsToMany(Role::class);
}

This allows the user to have multiple Roles (a User can be an Admin, a Moderator and a Basic user as well).

Also inside the User Model create a function or multiple functions to check the User Roles depending on your project needs:

public function isAdmin() {
   return $this->roles()->where('name', 'Admin')->exists();
}

public function isModerator() {
   return $this->roles()->where('name', 'Moderator')->exists();
}

etc...

Make sure that there is at least one user in the user table. Now you can add values to the role_user table.

From blade you can check if a user is an Admin or whatever roles you created, calling the functions we created inside the User Model:

@guest

   You are not logged in

@else

   You are logged in!

   @if(Auth::user()->isAdmin())
     You are an Admin, showing Admin options...
   @endif

   @if(Auth::user()->isModerator())
     You are a Moderator, showing Moderator options
   @endif

@endguest

Upvotes: 3

RobyB
RobyB

Reputation: 1416

After saw many answers that talks about isAdmin method in User class, I have to say that there's no need to create such method.

There is already the method HasRole

You can call this from artisan tinker from command line, just to see it before writing code:

php artisan tinker

Check if the user with id 1 has role 'user';

User::find(1)->hasRole('user');

Check if the user with id 1 has role 'admin';

User::find(1)->hasRole('admin');

The same way while coding for example in app.blade template:

@if (Auth::user()->hasRole('admin'))
   <p><a href="#" class="btn btn-success" role="button">Edite</a> <a href="#" class="btn btn-danger" role="button">Remove</a></p>

@endif

enter image description here

Upvotes: 0

Vlad
Vlad

Reputation: 33

Something that works for me.

In controller:

$user = Auth::user()->role()->where('name', 'admin')->exists();
return view('user.index', compact('user'));

In view:

@if($user)
    //enter code here ...
@endif

Upvotes: 1

UsmanJini
UsmanJini

Reputation: 11

@auth   

     @php 
     $user= auth::user()->id;
     @endphp 
    
    <div>{{$user}}</div> 

@else
 
    Auth is not login

@endauth

you can also get the user detail in view page by this mathod.

Upvotes: 0

Ali Irvani
Ali Irvani

Reputation: 21

you have to write below code in your UsersTable migration :

 $table->enum('role',  ['user', 'manager', 'admin'])->default('user');

in the second step Run migration , then define your gates in app/Providers/AuthServiceProvider.php like this :

namespace App\Providers;
  
use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;
use Illuminate\Support\Facades\Gate;
  
class AuthServiceProvider extends ServiceProvider
{
    /**
     * The policy mappings for the application.
     *
     * @var array
     */
    protected $policies = [
            
    ];
  
    /**
     * Register any authentication / authorization services.
     *
     * @return void
     */
    public function boot()
    {
        $this->registerPolicies();
   
        /* define a admin user role */
        Gate::define('isAdmin', function($user) {
           return $user->role == 'admin';
        });
       
        /* define a manager user role */
        Gate::define('isManager', function($user) {
            return $user->role == 'manager';
        });
      
        /* define a user role */
        Gate::define('isUser', function($user) {
            return $user->role == 'user';
        });
    }
}

now you can use isAdmin , isUser , isManager methods in your view.blade files

like this

  @can('isAdmin')
      <div class="btn btn-success btn-lg">
          You have Admin Access
      </div>
  @elsecan('isManager')
      <div class="btn btn-primary btn-lg">
          You have Manager Access
      </div>
  @else
      <div class="btn btn-info btn-lg">
          You have User Access
      </div>
  @endcan

and after all there are many other ways to do it; you can refer to this link for more details my source

Upvotes: 2

Arnoldkk
Arnoldkk

Reputation: 587

if you have a role column attached to your users table then do this

In the User model in the User.php file add this

public function isAdmin() {
  return $this->role == 'admin'
}

public function isCouple() {
  return $this->role == 'couple'  
}

public function isServiceProvider() {
  return $this->role == 'serviceProvider'
}

In your blade use this

@if(Auth::user()->isServiceProvider())
 //am a service provider
@endif

Upvotes: 2

devnull
devnull

Reputation: 1928

First of all you need to create the role table that contain the roles details. (I'm assuming Each user may have multiple roles not only Administrator)

Roles Table:

    Schema::create('role', function (Blueprint $table) {
        $table->increments('id');
        $table->string('name');
    });

Then

user_role Table:

Schema::create('user_role', function (Blueprint $table) {
    $table->bigInteger('user_id')->unsigned();
    $table->integer('role_id')->unsigned();
    $table->foreign('user_id')
        ->references('id')->on('users');
    $table->foreign('role_id')
        ->references('id')->on('roles');
});

Create Role model:

php artisan make:model Role

Afterwards add the roles relationship to the user model:

class User extends Authenticatable {
    public function roles() {
        return $this->belongsToMany(Role::class, 'user_role');
    }
}

To check if user has Administrator role you can do something like:

@if($user->roles()->where('name', 'Administrator')->exists())
enter code here
@endif

Or instead of doing this statement you can put as function in the User model as below:

public function isAdministrator() {
   return $this->roles()->where('name', 'Administrator')->exists();
}

Then in your model you can call it:

@if(Auth::user()->isAdministrator())
enter code here
@endif

Other possibility (1 - 1) Relation

First add is_admin column in your migration:

public function up()
{
    Schema::create('user', function (Blueprint $table) {
        $table->increments('id');
        $table->string('name');
        $table->string('email')->unique();
        $table->string('password');
        $table->boolean('is_admin')->default(0);
        $table->rememberToken();
        $table->timestamps();
    });

Then you can check:

@if($user->is_admin)

@endif

Upvotes: 35

Abdulmajeed
Abdulmajeed

Reputation: 580

@auth
    @if(auth()->user()->role_id == 1)
       i am Admin
    @endif
@endauth

Upvotes: 0

Md Azizur Rahman
Md Azizur Rahman

Reputation: 375

@if (Auth::guard($guard)->check() && Auth::user()->role->id==1)  
          return redirect()->route('admin.dashboard');
  @endif

Upvotes: 2

Martin
Martin

Reputation: 1

In laravel 5.5. this worked for me :

@if(Auth::check() && Auth::user()->role['name'] == "admin")
   // You are an Admin                    
@endif

Upvotes: 0

Abhishek
Abhishek

Reputation: 3967

Standard way is to do what xdevnull mentioned. But for small projects you can do something like this:

If(Auth::check() && Auth::user()->isAdmin()) {
  dd("you are admin") ;
}

And in your User model create a method isAdmin()

function isAdmin() {
  $admin_emails = config('settings.admin_emails');
  if(in_array($this->email, $admin_emails)  return true;
  else return false;
}

Of course you need to create a config file called settings in your app/config folder.

And put this in settings.php

<?php
return ['admin_emails' => explode(', ',  env('ADMIN_EMAILS'));]

And finally in your .env file add this: [email protected],[email protected]

Add as much emails as you want spayed by commas.

Now if logged in user has email as [email protected] or [email protected] then she is Admin.

Also notice I have added admin emails in env file so that admins can be changed depending on the environment. In development usually developer is the admin while in production somebody else (client?) is the admin.

P.S. don't forget to run php artisan config:cache after creating your settings.php file

Upvotes: 14

Achraf Khouadja
Achraf Khouadja

Reputation: 6279

here u go

  @if(Auth::check() && Auth::user()->role == "admin")

  @endif

you have to role attribute to your database and it should contain admin or anything else (you can use bolean attribute too)

Upvotes: 2

Related Questions