Reputation: 176
I'm using a view composer to store global variable on all views $currency
from sessions() for all views.
My view Composer.php
:
public function __construct(
protected Request $request,
) {}
public function compose(View $view): void
{
$currency = $this->request->session()->get('currency', config('app.currency') );
app\Providers\ViewServiceProvider.php
public function boot()
{
Facades\View::composer('*', CurrencyComposer::class);
}
But my problem is I'm getting the following error on the error pages 404 page
Session store not set on request
I have tried the solution found here
protected $middleware = [
//...
\Illuminate\Session\Middleware\StartSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
];
Which does fix my issue but then I'm unable to set any sessions it will refresh all session on every page load.
Upvotes: 2
Views: 697
Reputation: 176
Use a closure based composers in ViewServiceProvider. Using a if statement to check if session is set before setting the $view.
app\Providers\ViewServiceProvider.php
public function boot()
{
Facades\View::composer('*', function ($view) {
if (session()->has('currency')) {
...
$view->with([
'currency' => $currency,
]);
}
}
}
Upvotes: 0
Reputation: 1216
You can just do the wildcard with the folder name :
Facades\View::composer('livewire/*', CurrencyComposer::class);
It will only share the views under the livewire
folder inside the views
folder. Or if you want more specific
Facades\View::composer(['livewire/admin/*','livewire/guest/*'], CurrencyComposer::class);
Upvotes: 0
Reputation: 14535
As you may have already found out, the session is only available when the StartSession middleware is applied to the route.
Alternatively, you can also consider using the cookie, which is available to all routes. For example, you can create a custom view for the 404 error page at resources/views/errors/404.blade.php, and read the cookie using the request() helper."
<?php
$cookie = request()->cookie('xxx-you-used-for-the-currency');
echo $cookie;
Upvotes: 0