Home > database >  How to have superuser on laravel 8 UI
How to have superuser on laravel 8 UI

Time:05-10

We have build a user auth with laravel UI by having accounts -> users structure. Now we want to have a superuser, that can see all data from all accounts.

Is there any how-to or best practice how to support this?

Could be a new column on users table named "super_user" true/false for example.

Thank you

CodePudding user response:

You can add a column in DB as you said and every time check it with a middleware. for example:

  • Create a middleware in app/Http/Middleware

  • Add route middleware to protected $routeMiddleware in app/Http/Kernel.php

  • Use this middleware in routes/web.php or in constructor function in related controllers like this example:

    public function __construct() {
    $this->middleware('superUser'); }

CodePudding user response:

You can do in in several ways but I can give you some example: First create this middleware with this name (UserCheck) then put this block of code inside:

use Illuminate\Support\Facades\Auth;
public function handle(Request $request, Closure $next)
    {

    $user = Auth::user();
    $usertype = $user->type;
    if ($usertype == 1) { 
    return $next($request);
    }
    else{
        return redirect('home');
    }
    
}
}

so with this code you can check the status of the user 1 for super user and 2 for users so do not forget to add this line in karnel.hp

'admincheck' => \App\Http\Middleware\UserCheck::class,

for your data base add one line and migrate it

    $table->boolean('type')->nullable();

also in your model add type of user like this:

 protected $fillable = [
        "user_id",
       ];

now you can use this middleware in your constructor like this :

public function __construct()
    {
        $this->middleware('Usercheck');
       
    }

CodePudding user response:

Adding a field to a table can be the easiest way :)

CodePudding user response:

the best way you can add a third-party framework https://github.com/spatie/laravel-permission for role and permission to optimize all events in your application

  • Related