I have a few custom middlewares defined in App\Http\Kernel.php, after the ones that ship with Laravel:
protected $routeMiddleware = [
'auth' => \App\Http\Middleware\Authenticate::class,
'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
'cache.headers' => \Illuminate\Http\Middleware\SetCacheHeaders::class,
'can' => \Illuminate\Auth\Middleware\Authorize::class,
'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
'password.confirm' => \Illuminate\Auth\Middleware\RequirePassword::class,
'signed' => \Illuminate\Routing\Middleware\ValidateSignature::class,
'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
'verified' => \Illuminate\Auth\Middleware\EnsureEmailIsVerified::class,
// Custom Middleware
'custom1' => \App\Http\Middleware\Custom1::class,
'custom2' => \App\Http\Middleware\Custom2::class,
'custom3' => \App\Http\Middleware\Custom3::class,
];
In Custom1 I use auth('web')->user()->id which gives the error Trying to get property 'id' of non-object.
This error happens sometimes, not always, in my production environment and it's difficult to figure out why.
My guess is that the user is not authenticated for some reason (session expired?). If that's the case then I'm wondering why the auth middleware doesn't catch this.
Further down in the Kernel file there is:
protected $middlewarePriority = [
\Illuminate\Session\Middleware\StartSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
\App\Http\Middleware\Authenticate::class,
\Illuminate\Routing\Middleware\ThrottleRequests::class,
\Illuminate\Session\Middleware\AuthenticateSession::class,
\Illuminate\Routing\Middleware\SubstituteBindings::class,
\Illuminate\Auth\Middleware\Authorize::class,
];
Could it be that the Custom1 middleware is executed before the auth middleware and should I add it at the end of $middlewarePriority?