Search code examples
laravelmiddleware

Laravel Middleware -> get the logged in user


I want to write my own middleware to check, if the current user is member of a certain grup. If yes, the user can move on to the route, if not, the user will be redirected to a different page.

My middleware is working, but I don't know how to get the current users id. I've tried the Auth::user() method, but with no success.

This is my Middleware:

namespace App\Http\Middleware;

use Closure;
use App\User;
use App\Usergroups;
use Illuminate\Http\Request;

class UserGroupMiddleware
{
     /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
     public function handle(Request $request, Closure $next, $group = NULL)
    {
        $user_id = $request->user()->user_id;
        $user = User::find($user_id);
        $usergroup = Usergroups::find($user->benutzergruppe);

        if($usergroup->slug == 'admin'){
            return $next($request);
        }
        return redirect('/');
    }
}

Solution

  • You have access to the currently authenticated user, if it’s been resolved. That means you need to make sure you place your group-checking middleware after the auth middleware on your route/route group:

    Route::group(['middleware' => ['auth', 'in_group:group_name']], function () {
        // Routes
    });
    

    You can then check a role like this:

    class UserGroupMiddleware
    {
        public function handle(Request $request, Closure $next, $group)
        {
            // Check user is in specified group here
            if ($request->user()->memberOf($group)) {
                return $next($request);
            }
    
            // Display a 403 Forbidden error
            abort(403);
        }
    }