Reputation: 161
I'm trying to build an authentication middleware for admin but I got Trying to get property 'is_admin' of non-object
namespace App\Http\Middleware;
use Illuminate\Support\Facades\Auth;
use Closure;
class Admin
{
public function handle($request, Closure $next)
{
if(auth()->user()->is_admin == 1){
return $next($request);
}
return redirect()->route('login');
}
and when I printed dd(auth()->user()) it returned null
Upvotes: 1
Views: 3215
Reputation: 4750
auth()->user()
is returning null
Why?
Because the user is not logged in.
So, you can modify your condition from:
if(auth()->user()->is_admin == 1)
To:
if(auth()->check() && auth()->user()->is_admin == 1)
Upvotes: 7