Warm tip: This article is reproduced from stackoverflow.com, please click
laravel-5 php redirect

laravel constructor redirect

发布于 2020-04-05 23:37:04

I have a method for checking if a user's role is an admin, if not, redirect them with return redirect('/')->send();. How can I check for user role and redirect the user without displaying the page and waiting for a redirect?

My Controller:

class AdminController extends Controller
{
    public function __construct()
    {
        if (Auth::check())
        {
            $user = Auth::user();
            if ($user->role != 'admin')
            {
                return redirect('/')->send();
            }
        }
        else
        {
            return redirect('/')->send();
        }
    }

    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        return View('admin/index');
    }
}
Questioner
lock
Viewed
61
Brotzka 2016-07-04 13:31

Create your own Middleware. Here is an example. In my example, I have several usergroups in a separate model. You have to change the code for your needs.

Create the Middleware via terminal/console:

php artisan make:middleware UserGroupMiddleware

The created middleware class could be find in app/Http/Middleware/UserGroupMiddleware.php

You need the following code in your middleware:

namespace App\Http\Middleware;

use Closure;
use App\User;
use App\Usergroup;

class UserGroupMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next, $group)
    {
        if($request->user() !== NULL){
            $userGroupId = $request->user()->group;
            $userGroup = Usergroup::find($userGroupId);

            if($userGroup->slug === $group){
                return $next($request);
            }
        }
        // Redirect the user to the loginpage
        return redirect('/login');
    }
}

Now you have to register this middleware in app/Http/Kernel.php:

protected $routeMiddleware = [
    // other middlewares

    // Custom Middleware
    'group' => \App\Http\Middleware\UserGroupMiddleware::class
];

Finally you need to attach the middleware to your route:

Route::group(['middleware' => 'group:admin'], function(){
    // Routes for admins, e.g.
    Route::get('/dashboard', 'SomeController@dashboard');
});

// Or for a single route:
Route::get('/dashboard', ['middleware' => 'group:admin'], function(){
    return view('adminbereich.dashboard');
});

Remember, that you could pass in multiple middlewares with:

Route::get('/some/route', ['middleware' => ['group:admin', 'auth']], 'SomeController@methodXYZ');