Home > OS >  Laravel share data to 404 page view
Laravel share data to 404 page view

Time:06-15

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

CodePudding user response:

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.

CodePudding user response:

After some trial and error the issue was that the StartSession middleware was not being executed in the 404 error page, also had to move from the Controller to AppServiceProvider to make it work correctly.

Added to kernel.php $middleware

\Illuminate\Session\Middleware\StartSession::class,

Also to appServiceProvider.php boot()

        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