By "custom 404 page", you mean adding a 404.blade.php to /views/errors/?
Getting Auth::user() on custom 404 page.
I'm using the built in make:auth stuff. However, on a custom error page, Auth::user() returns null.
I'm using a template that adds certain content using @if(Auth::guest()) ... @else ... @endif, so I would still like the nav bar pages to appear to a user even if they get to a 404 page.
Is there a way to make the custom error pages have access to Auth::user(), etc.?
Yes, that's what I mean.
If you're using 5.2, it's probably because the web middleware is not being loaded.
How do I go about loading it? --I'm pretty new to Laravel.
I'd have to check, not really sure on why it wouldn't work. Haven't used 5.2 that much yet.
Hi, was anybody able to find a solution for this issue?
I still haven't been able to figure it out. I ended up just making a 404 page without any of the "user logged in" links. :(
Is the user actually logged in?
If you have Laravel 5.2.28 >= and you have the web middleware on your routes, remove it. The web middleware is built into all routes from 5.2.28 onwards.
If you are below 5.2.28, make sure you have the web middleware on the 404.
@stevenjeffries Assuming you are using Laravel 5.2
Open app/Http/Kernel.php. Add below block to the $middleware
\Illuminate\Session\Middleware\StartSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
so your code should like this:
/**
* The application's global HTTP middleware stack.
*
* These middleware are run during every request to your application.
*
* @var array
*/
protected $middleware = [
\Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
\Illuminate\Session\Middleware\StartSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
];
Now you should be able to access Auth in your views/errors/404.blade page. Make sure you put a '\ ' before Auth. For Eg:
{{\Auth::user()->name}}
Thanks! That would work. Is there any downsides to adding this go the global middlewares? I'm sure there's a reason this isn't like this as default? Didn't it use to be in an older version of laravel?
Thanks again @vipindasks
@arctic-ice-cool When a middleware is added to the global, each and every requests to the application will have to pass through that particular middleware. That is why they are not added globally by default.
Thanks, is it possible to add the middleware specifically to 404 error pages, without globally running the middleware? As this could hinder the development of stateless API sections of an app?
Thanks!
Any update on how do this so it doesn't affect api routes, i.e. apply the middleware to only error pages?
this is what I'm using to avoid this issue
app/Http/Kernel.php
protected $middleware = [
\Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
\App\Http\Middleware\EncryptCookies::class,
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
\Illuminate\Session\Middleware\StartSession::class,
];
protected $middlewareGroups = [
'web' => [
//\App\Http\Middleware\EncryptCookies::class,
//\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
//\Illuminate\Session\Middleware\StartSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
\App\Http\Middleware\VerifyCsrfToken::class,
\Illuminate\Routing\Middleware\SubstituteBindings::class,
],
'api' => [
'throttle:60,1',
'bindings',
],
];
@molayli Thanks it works! Yaayyy :D
I've tried this on Laravel 5.3 and it worked indeed, however, the validation for /login stopped working..
This was probably because you've applied middleware twice - once within global middleware group and once within web middleware group...
this solutions made the users keep getting logged out, every time
The solution provided by @vipindasks and @molayli makes the API routes vulnerable for CSRF attacks.
Since I didn't see this answer here, if you are using Laravel 5.5 or later, you can use the new Route::fallback(): https://laravel-news.com/laravel-v5-5-5
If you use that new feature then you don't have to move your StartSession or ShareErrorsFromSession middleware to the global $middleware array.
@jonbnewman Thank you for the solution with Route::fallback()
One of the sort of hacks until you upgrade to 5.5 and want to have an API without a state is to create a route which prints your custom 404 page. And redirect on 404 error to this route. No the cleanest and proper way, but does the job.
Route::any('/404', function() {
return View::make('errors.missing', [], 404);
});
So does anyone know how to sort this for those requests that come in right after the user session has expired, but you have remember me enabled for the login? It does not seem like Laravel manages to re-arm the user session in time for the view render, so the Auth::check() remains false, and Auth::user() remains null.
If I manually go to a non-error page in the application, thus having Laravel re-reading my remember me cookie and setting up a new session before render, and then go back to a page that triggers an error (404 for instance), the user object and Auth facade works as it should.
I have tested this by setting SESSION_LIFETIME=1 in my .env, closed the tab in my browser, waited a minute, and then re-opened the 404 page directly (f.ex http://my.app/404).
If you want to filter request from /admin/* & for /* you can use Request helper function Like this:
@if (Request::is('admin/*')) Go To Dashboard @else Go Back To Home @endif
Hope it helps. Thanks
So making every request load up the start session is probably not a great idea.
Try this instead (loading the session on the fact its a 404 exception being thrown):
app/Exceptions/Handler.php
protected function renderHttpException(HttpExceptionInterface $e)
{
if ($e instanceof NotFoundHttpException) {
/** @var StartSession $sessionMiddleware */
$sessionMiddleware = resolve(StartSession::class);
/** @var EncryptCookies $decrypter */
$decrypter = resolve(EncryptCookies::class);
$decrypter->handle(request(), fn() => $sessionMiddleware->handle(request(), fn() => response('')));
}
return parent::renderHttpException($e);
}
Instead try this end of file => routes/web.php
example:
// error page
Route::fallback(function() {
if ($exception = new \Symfony\Component\HttpKernel\Exception\NotFoundHttpException()) {
$code = $exception->getStatusCode();
if(Str::is(admin_url_prefix().'*', request()->path())) {
if (! is_null($user = Auth::guard('author')->user())) {
$url = Request::url();
$sidebarItems = EventedAdminMenu::get('backend.menu.sidebar', $url);
} else {
$sidebarItems = array();
}
return response()->view('platform::backend_theme.errors.'.$code, compact('sidebarItems', 'url'), $code);
} else {
return response()->view('platform::frontend.errors.'.$code, [], $code);
}
}
});
example : html 404.blade.php
<x-platform::backend-layout :sidebarItems="$sidebarItems">
<x-slot name="header">
<ol class="breadcrumb">
<li class="breadcrumb-item active" aria-current="page">Home</li>
</ol>
</x-slot>
<div class="main-wrapper">
<div class="page-wrapper full-page">
<div class="page-content d-flex align-items-center justify-content-center">
<div class="row w-100 mx-0 auth-page">
<div class="col-md-8 col-xl-8 mx-auto d-flex flex-column align-items-center">
<img src="{{ Module::asset('platform:backend-theme/assets/images/others/404.svg') }}" class="img-fluid mb-2" alt="404">
<h1 class="fw-bolder mb-22 mt-2 tx-80 text-muted">404</h1>
<h4 class="mb-2">Page Not Found</h4>
<h6 class="text-muted mb-3 text-center">Oopps!! The page {{ $url }} you were looking for doesn't exist.</h6>
<a href="#" onclick="goBack()">Back to home</a>
</div>
</div>
</div>
</div>
</div>
<script>
function goBack() {
window.history.back();
}
</script>
</x-platform::backend-layout>
Please or to participate in this conversation.