Hello folks,
I am facing a challenge which I have usually solved by using singletons or view composers. I need to share the cart instance with the items that are in cart. Each time cart is retrieved it's from the database and based on auth()->check() I decide whether to use SessionRepository or DatabaseRepository in the app.
We are also storing both session carts as well as specific user carts in the database due to marketing analysis reasons.
My problem is that so far I have been using view composer with the layout view for sharing the current cart instance like this:
view()->composer('frontend.site._layouts.*', function ($view) {
$cart = Cart::retrieve();
if (!$cart) {
$cart = Cart::store();
}
app()->scoped('cart', function () use ($cart) {
return $cart;
});
$view->with('cart', $cart);
});
As you can see I am sharing it with views while also making a scoped cart instance which I for example access in my livewire components.
Problem is that this solution is no the best because on certain pages like the cart.index page I need the cart in the CartController but the app->cart is not yet set because it is set to run in the view composer. You might as why? Well that's because if it runs regularly in the CartServiceProvider I receive error due to the fact that user and it's provider has no run yet and user object is not yet available even if i placed the provider on last spot in app.php.
Target class [hash] does not exist.
So I run fetching of the cart in the CartController again and perform some operation with it so that it's available on the cart index page . This causes fetching of the cart twice which I would like to avoid.
Is there some best practice for my problem? Sharing eloquent query results where auth()->user is used within the query via provider / view composer while still being available within controllers / middlewares and views? I appreciate every response. Thank you!