Laravel Middleware return user info as null

I created a middle to prevent a user to not to insert or update anything. I am on Laravel 5.6

<?php

namespace AppHttpMiddleware;

use Closure;
use IlluminateSupportFacadesAuth;
class LimitDemoUser
{
    /**
     * Handle an incoming request.
     *
     * @param  IlluminateHttpRequest  $request
     * @param  Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $userId = Auth::id();
        if(request()->method() != "GET" && request()->method() != "HEAD" && $userId == 6) {
            abort(403);
        }
        return $next($request);
    }
}

I registered it to kernel like this ( LimitDemoUser )
protected $middleware = [
    IlluminateFoundationHttpMiddlewareCheckForMaintenanceMode::class,
    IlluminateFoundationHttpMiddlewareValidatePostSize::class,
    AppHttpMiddlewareTrimStrings::class,
    IlluminateFoundationHttpMiddlewareConvertEmptyStringsToNull::class,
    AppHttpMiddlewareTrustProxies::class,
    AppHttpMiddlewareLimitDemoUser::class,

];

But when I dd(Auth::id()); I got null rather than gettin loggedin user id

What am I missing here?

I suppose I don’t have o add anything to routemiddleware

protected $routeMiddleware = [
    'auth' => IlluminateAuthMiddlewareAuthenticate::class,
    'auth.basic' => IlluminateAuthMiddlewareAuthenticateWithBasicAuth::class,
    'bindings' => IlluminateRoutingMiddlewareSubstituteBindings::class,
    'cache.headers' => IlluminateHttpMiddlewareSetCacheHeaders::class,
    'can' => IlluminateAuthMiddlewareAuthorize::class,
    'guest' => AppHttpMiddlewareRedirectIfAuthenticated::class,
    'throttle' => IlluminateRoutingMiddlewareThrottleRequests::class,

];

My LoginController is below. Maybe it may help
<?php

namespace AppHttpControllersAuth;

use AppHttpControllersController;
use IlluminateFoundationAuthAuthenticatesUsers;

class LoginController extends Controller
{
    /*
    |--------------------------------------------------------------------------
    | Login Controller
    |--------------------------------------------------------------------------
    |
    | This controller handles authenticating users for the application and
    | redirecting them to your home screen. The controller uses a trait
    | to conveniently provide its functionality to your applications.
    |
    */

    use AuthenticatesUsers;

    /**
     * Where to redirect users after login.
     *
     * @var string
     */
    protected $redirectTo = '/login';

    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('guest')->except('logout');
    }

    public function logout()
    {
        $this->guard()->logout();

        return redirect()->route('login');
    }

}

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

Add the AppHttpMiddlewareLimitDemoUser::class to the end of web middleware group array.

protected $middlewareGroups = [
    'web' => [
        ...,
        AppHttpMiddlewareLimitDemoUser::class,
     ]
];

Method 2

Your loginController should be as below:

class LoginController extends Controller
{
    /**
     * Handle an authentication attempt.
     *
     * @return Response
     */
    public function authenticate()
    {
        if (Auth::attempt(['email' => $email, 'password' => $password])) {
            // Authentication passed...
            return redirect()->intended('dashboard');
        }
    }
}

When you want to get the user id, you should the user class.
if (Auth::check())
{
    // The user is logged in...
    Auth::user()->id;
}
else
{
    echo "You are not logged in";
}

Method 3

Try changing your web.php to

Route::middleware(['limitdemouser'])->group(function () {
  Auth::routes();
});

and your $routeMiddleware is
protected $routeMiddleware = [
    'auth' => IlluminateAuthMiddlewareAuthenticate::class,
    'auth.basic' => IlluminateAuthMiddlewareAuthenticateWithBasicAuth::class,
    'bindings' => IlluminateRoutingMiddlewareSubstituteBindings::class,
    'cache.headers' => IlluminateHttpMiddlewareSetCacheHeaders::class,
    'can' => IlluminateAuthMiddlewareAuthorize::class,
    'guest' => AppHttpMiddlewareRedirectIfAuthenticated::class,
    'throttle' => IlluminateRoutingMiddlewareThrottleRequests::class,
    'limitdemouser' => AppHttpMiddlewareLimitDemoUser::class,
];

Let me know if not works

Method 4

I found the solution in this page.
https://laracasts.com/discuss/channels/laravel/current-user-in-middleware

OP stated

i have added the following code in the global middleware and nou is het working 
AppHttpMiddlewareEncryptCookies::class, IlluminateSessionMiddlewareStartSession::class,

It is dirty but it worked. I don’t think that this is the best practice but it solved the problem. Since we found the problem, from here can someone suggest a decent solution?


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x