Support the ongoing development of →
Blade Routing
Last updated by @ajax30 1 year ago.

ddiskandar liked this thread


I would do it by having a static method that yoy call from your Blade views to compute (if not in cache), cache and return your variables


You can use the View facade's share method.

View::share('key', 'value');

The link to the official documentation is Sharing Data With All Views


I think your sidebar view is a good fit for a Blade Component. You have the option to calculate the needed values in the component class.


@tvbeek I need all 3 variables to be "visible" at once. I also use them to display the pagination container only if necessary.

Last updated by @ajax30 2 years ago.
moderator Solution

You can create the component, then you get something like:

namespace App\View\Components;
use Illuminate\View\Component;
class Sidebar extends Component
    public int $articleCount = 0;
    public int $categoryCount = 0;
    public int $commentsCount = 0;

    public function render() {
        $this->articleCount =  Article::count();
        $this->categoryCount =  Category::count();
        $this->commentsCount =  Comment::count();
        return view('components.sidebar')

With a component view like:

<ul class="list-group list-group-flush">
	<li class="list-group-item">
		<a class="{{ request()->routeIs('dashboard.articles*') ? 'active' : '' }}" href="{{ route('dashboard.articles') }}">
			<span class="badge">{{ $articleCount }}</span>
	<li class="list-group-item">
		<a class="{{ request()->routeIs('dashboard.categories*') ? 'active' : '' }}" href="{{ route('dashboard.categories') }}">
			<span class="badge">{{ $categoryCount }}</span>
	<li class="list-group-item">
		<a class="{{ request()->routeIs('dashboard.comments*') ? 'active' : '' }}" href="{{ route('dashboard.comments') }}">
			<span class="badge">{{ $commentsCount }}</span>

And use it in your blade file like this


Small note about what I see in your code but not related to your question:
Article::all()->count(); will load all the articles and execute a count on that collection. This will populate all the models can use a lot of memory and request time.
But Article::count(); will execute a count query and only returns the number without creating all the models in memory.

Solution selected by @ajax30

@tvbeek Wich code belongs in the component?


@tvbeek Please help me with this issue too. Thanks!


An alternative to the solution proposed is you can use View Composer to return the counts to the view that you want.


Sign in to participate in this thread!


Your banner here too?

Razvan ajax30 Joined 2 Oct 2021


We'd like to thank these amazing companies for supporting us

Your logo here?

The Laravel portal for problem solving, knowledge sharing and community building.

© 2024 - All rights reserved.