Laravel share data to 404 page view

Viewed 50

I have created a controller which extends BaseController and shares some data in all the views

class Controller extends BaseController
{
    use AuthorizesRequests, DispatchesJobs, ValidatesRequests;

    public function __construct()
    {
        $this->middleware(function ($request, $next) {
            if (Auth::check()) {
                $id = Auth::id();
            } else {
                $id = Session::getId();
            }

            \Cart::session($id);

            $cart = \Cart::getContent();

            $total = \Cart::getTotal();
        
            View::share('cart', $cart);
            View::share('total', $total);

            return $next($request);
        });
    }

}

The issue is, it doesn't get shared in error pages like 404.

I'm using Laravel 8.75

2 Answers

First you should publish all the error pages using this command:

php artisan vendor:publish --tag=laravel-errors

Then, hopefully it will work. If it didn't work then include this logic in AppServiceProvider's boot() function instead of base Controller.

After some trial and error the issue was that web middleware was not being executed in error pages.

Added to web.php

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

Also to appServiceProvider.php boot() (optional)

        View()->composer(['layouts.main'], function($view) {
            if (Auth::check()) {
                $id = Auth::id();
            } else {
                $id = Session::getId();
            }

            \Cart::session($id);

            $cart = \Cart::getContent();

            $total = \Cart::getTotal();

            $view->with([
                'cart' => $cart, 
                'total' => $total
            ]);
        });

The reason i put the auth checking inside the view composer callback is because middlewares have to be executed to be able to grab the user.

Related