Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel can't see if a user is logged in on 404 error page

Tags:

laravel

I have created a custom 404 error page and I am using my app.layout to wrap it.

But it's strange because when i get 404 error page even though I'm logged in the Login and Register links are seen. Why is that?

enter image description here

update

when i log in on my page and write non existing route i get my 404 page with extended layout but it seems like Laravel doesn't have access to Auth::class and it doesn't see if a user is logged in or not.

So instead of seeing Logout link i see "Login" and "Register" links

like image 701
lewis4u Avatar asked Feb 23 '17 14:02

lewis4u


2 Answers

Add this below to /routes/web.php:

Route::fallback(function(){
    return view('errors.404');
});

and add a new file /resources/views/errors/404.blade.php:

Nothing here {{ Auth::user()->name }}: 404!

Of course, you can change this template to extend any template you want to use.

Available from v5.5.5

like image 106
brnd0 Avatar answered Oct 16 '22 17:10

brnd0


Check if your app.layout included a nav partial.

a layout html like this :

<div class="content-wrapper">
 <!-- Content Header (Page header) -->
 @include('partials.crumble_head')
 <!-- Main content -->
 <section class="content">
  @yield('content')
 </section>
 <!-- /.content -->
</div>

if your content page extends this layout, then partial will not disapear

Hi, The answer needs to be updated based on what we discussed.

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}}

https://laracasts.com/discuss/channels/laravel/getting-authuser-on-custom-404-page

like image 29
Raymond Cheng Avatar answered Oct 16 '22 17:10

Raymond Cheng