The error "Call to a member function roles() on null" occurs when the Auth::user() method returns null, meaning that there is no authenticated user. To fix this issue, you need to ensure that the user is authenticated before accessing their roles.
Here's an updated version of the handle method in the Admin middleware that includes the necessary check:
public function handle(Request $request, Closure $next): Response
{
if (Auth::check()) {
$adminRole = Auth::user()->roles()->pluck('name');
if ($adminRole->contains('admin')) {
return $next($request);
}
}
// Handle unauthorized access here
abort(403, 'Unauthorized');
}
In this updated code, we first check if the user is authenticated using the Auth::check() method. If the user is authenticated, we proceed to retrieve their roles and check if they contain the 'admin' role. If the condition is true, we allow the request to proceed by calling $next($request). Otherwise, we abort the request with a 403 (Unauthorized) status code.
Make sure to import the necessary classes at the top of your file:
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;
use Closure;
use Illuminate\Support\Facades\Auth;
Remember to replace Role::class with the actual class name of your Role model if it's different.
I hope this helps! Let me know if you have any further questions.