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

Marcolino922's avatar

Retrieve a model in blade file

Hi, by necessity I find myself having to implement model references in portions of layouts. I wanted to know if using this (example) directly in the blade file:

@inject('totalItems', 'App\Models\Items')
{{ $totalItems->where('status', 1)->count() }}

Is it a "safe" method?

0 likes
9 replies
tykus's avatar

Unconventional, yes. Unsafe, no.

What prevents you organising this data in a Controller, or View Composer?

Marcolino922's avatar

The same is true for?

{{ App\Models\Items::where('status', 1)->count() }}

Anyway, I need to find the count of all the elements, or find all the categories in the header and footer and I wanted to avoid going through the controller because consequently I would have to pass the variable in every function. Instead I wanted to act directly on the template blade in order to simplify everything.

tykus's avatar

The same is true for?

Yes, maybe less non-conventional 😉

I would have to pass the variable in every function

This is when we reach for View Composers

Marcolino922's avatar

I was trying to understand better, but I don't understand how to pass data to blade. For example, I need to pass all categories from the Categories model in the blade navigation.blade.php file, how should I proceed?

PS: I mean, using View Composers

tykus's avatar

For simplicity, let’s just use a Closure. In the boot method of the AppServiceProvider class, add the following:

View::composer(‘navigation’, fn ($view) => $view->with(‘categories’, Category::all());

Ensure you have imported the correct namespaces for use Illuminate\Support\Facades\View; facade and App\Models\Category model.

What does this do? Whenever the navigation blade template is rendered, there will be a $categories variable available just as though passed from a Controller action.

Note, if navigation template is in a subdirectory, make sure you use the usual dot-syntax to reference the path relative to resources/views

crazy's avatar

@tykus i think you should define variable in controller and then you can pass in blade file otherwise can't pass variable dynamically

Please or to participate in this conversation.