Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

rudolfbruder's avatar

Sharing eloquent query result where auth()-user() object is used with views and across the application

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!

0 likes
2 replies
martinbean's avatar
Level 80

@rudolfbruder Use the service container properly. View composers are not a location you should be registering bindings.

Create some middleware that retrieves and binds the relevant cart and then it’ll be available in controllers, views, and where ever else you need it.

1 like
rudolfbruder's avatar

@martinbean You are right Middleware is probably the best place where to store such a logic and sharing feature. Many thanks!

1 like

Please or to participate in this conversation.