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.
You can create the component, then you get something like:
<?php
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') }}">
Articles
<span class="badge">{{ $articleCount }}</span>
</a>
</li>
<li class="list-group-item">
<a class="{{ request()->routeIs('dashboard.categories*') ? 'active' : '' }}" href="{{ route('dashboard.categories') }}">
Categories
<span class="badge">{{ $categoryCount }}</span>
</a>
</li>
<li class="list-group-item">
<a class="{{ request()->routeIs('dashboard.comments*') ? 'active' : '' }}" href="{{ route('dashboard.comments') }}">
Comments
<span class="badge">{{ $commentsCount }}</span>
</a>
</li>
</ul>
And use it in your blade file like this
<x-sidebar/>
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.
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!
The Laravel portal for problem solving, knowledge sharing and community building.
The community