Did you try this?
APP_DEBUG=false
in your .env file
I specify my routes like this
Route::get('/collection', [CollectionController::class, 'index'])->middleware('auth');
However, if I navigate to localhost/collection without being logged in, I get a Laravel error page with a RouteNotFoundException. This is useful for debugging, but I don't want it to appear in production code. Ideally, I'd like to display a 403 error instead. How do I acheive this?
I've attempted to wrap it in try/catchblock,but this doesn't catch the exception. Presumably because it is being handled by Laravel. ChatGPT suggested I put the following in my App\Exceptions\Handler class:
public function render($request, Throwable $exception)
{
if ($exception instanceof AuthorizationException) {
// Customize the response for AuthorizationException (403 Forbidden)
return response()->view('errors.403', [], 403);
}
return parent::render($request, $exception);
}
But this also didn't work. Surely there must be an easy way around this, as I'm sure it's a common thing to want to do.
I can also set APP_DEBUG=false in my .env file. This gets rid of the error message, but returns a 500 error, which is not the correct response code.
Edit:
I seem to have solved this.
Previously, my Authenticate middleware class looked like this:
<?php
namespace App\Http\Middleware;
use Illuminate\Auth\Middleware\Authenticate as Middleware;
use Illuminate\Http\Request;
class Authenticate extends Middleware
{
/**
* Get the path the user should be redirected to when they are not authenticated.
*/
protected function redirectTo(Request $request): ?string
{
return $request->expectsJson() ? null : route('login');
}
}
The problem seemed to be related to the return statement in redirectTo. I changed the line to the following:
return $request->expectsJson() ? null : 'login';
And this redirected the user to the login page. Not a 403 error, but at least I can handle the situation.
Please or to participate in this conversation.