Reputation: 10447
I'm using spatie permissions module for controlling roles and permissions within my site. I have added a bit to the Authenticate middleware. My Handle now looks like this:
public function handle($request, Closure $next, $guard = null)
{
if (Auth::guard($guard)->guest())
{
if ($request->ajax() || $request->wantsJson())
return response('Unauthorized.', 401);
return redirect()->guest('login');
}
if ( ! Auth::user()->can('access acp') )
{
if ($request->ajax() || $request->wantsJson())
return response('Unauthorised.', 403);
abort(403, "You do not have permission to access the Admin Control Panel. If you believe this is an error please contact the admin who set your account up for you.");
}
return $next($request);
}
So if the user isn't logged in we send them to the login page, otherwise we check if the have permissions to access the acp, and if not show them a 403 error. I've added a 403.blade.php to the views/errors folder. However when I run that code I just get a Whoops! and the developer tools show a 500 ISE is being returned. I don't understand why I'm not seeing my custom error page.
So far I've tried switching the environment to production and turning debug mode off but that doesn't show the page. I've also tried throwing an authorisation exception but that doesn't do anything different. I also tried using App::abort()
but again, I still got the 500 ISE.
I've tried Googling the issue but I can't find anyone else having this issue. I would really appreciate any help in getting this working.
Whoops returns
If I modify the code thusly
try
{
abort(403, "You do not have permission to access the Admin Control Panel. If you believe this is an error please contact the admin who set your account up for you.");
} catch ( HttpException $e )
{
dd($e);
}
then I get an instance of HttpException
with my error code and message, so why isn't that then showing a custom error page?
Upvotes: 4
Views: 10841
Reputation: 939
I've managed to get around this problem with the the code below (note that it is a Lumen app but it should work with Laravel)
routes.php
$app->get('/test', function () use ($app) {
abort(403, 'some string from abort');
});
resources/views/errors/403.blade.php
<html>
<body>
{{$msg}}
<br>
{{$code}}
</body>
</html>
app/Exceptions/Handler.php, modify render() function as below
public function render($request, Exception $e)
{
if ($e instanceof HttpException) {
$statusCode = $e->getStatusCode();
if (view()->exists('errors.'.$statusCode)) {
return response(view('errors.'.$statusCode, [
'msg' => $e->getMessage(),
'code' => $statusCode
]), $statusCode);
}
}
return parent::render($request, $e);
}
It does what the Laravel should do according to docs
Upvotes: 6