John Davidson

php - Letting user access webpage if he has a certain role

0 comments
Message:


I am making a small webpage with Laravel that has User and Admin roles.
My 'users' table consists of name, email, password and role value (0 for user, 1 for admin).


I dont need anything fancy so can I just make it so every time a normal user loads in a page that's meant for the administrator - he gets redirected?


To be more precise: How can I make it so whenever a new page loads, the users role gets checked and then my if or can statement checks if the users allowed to access the page?


For example I have a view:
results that displays all the match results(can be accessed by everyone) and I also have an admin/RESULTSadmin view, that should only be accessed by a user that has an admin role but the rest needs to get redirected. Thank you in advance!



My Answer:
You can achieve this by using Laravel's middleware feature.

First, create a middleware that checks if the user has the admin role. You can do this by running the following command in your terminal:

bash
php artisan make:middleware AdminMiddleware


This will create a new middleware file in your `app/Http/Middleware` directory. Open the `AdminMiddleware.php` file and add the following code:

php

namespace App\Http\Middleware;

use Closure;

class AdminMiddleware
{
public function handle($request, Closure $next)
{
if(auth()->user() && auth()->user()->role == 1) {
return $next($request);
}

return redirect('/');
}
}


Next, register the middleware in your `app/Http/Kernel.php` file. Add the following line to the `$routeMiddleware` array:

php
'admin' => \App\Http\Middleware\AdminMiddleware::class,


Now, you can apply the middleware to your routes. In your routes file (usually `web.php`), you can use the `middleware` method to apply the `admin` middleware to the routes that should only be accessible by admins:

php
Route::get('admin/results', 'AdminController@results')->middleware('admin');


This will ensure that only users with the admin role can access the `results` page in the `AdminController`. Other users will be redirected to the home page.

Rate this post

5 of 5 based on 5894 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us