K
K
Kerm2019-10-23 13:26:29
Laravel
Kerm, 2019-10-23 13:26:29

Is it a good solution to output the result from the controller directly in the blade template?

I am new to Laravel, in the process of creating a site, it became necessary to create a module responsible for displaying a horizontal, vertical menu of categories and sections of the site, including the footer of the site. I note that by module I mean a site component that can be connected and displayed anywhere in the template.
I created a controller, a class for the controller, my own templates for the controller.
And I output in the template, in the place I need, the result with such a line of code, for example, in header.blade.php:

{{(new App\Http\Controllers\MenuController)->init('horizontal')}}

At first I wanted to display through variables like {{$menu_horizontal}}, but I was confused by what we say in the IndexController.php main page controller, I will have to refer to another controller, when google found a record that referencing from one controller to another is not good practice and the solution and did not quite understand how to implement it, all the more so.
In this regard, the question is, is such a call from the blade template to the controller normal or is it all here and say I should better abandon the controller in my module and make a normal class + my own blade template and output through variables in the template I need?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Alexander Kovalchuk, 2019-10-23
@Kerm

In such cases it is better to use inject

@inject('metrics', 'App\Services\MetricsService')

<div>
    Monthly Revenue: {{ $metrics->monthlyRevenue() }}.
</div>

Also, make this service a singleton where it will take data from the database in the constructor, and in the methods it will not give multiple requests in this way, even if one component connects to the page several times
PS Here in the answers there was another option to share variables in the provider, but for some reason the author removed it, but the option is quite good when the code is definitely on each page (for example, the menu)
So it's best to try two options and then decide which one is more convenient in your case

V
Vladimir Kokhan, 2019-10-23
@SkazochNick

And what does not fit the option through the service provider? In such cases, I just write to the AppServiceProvider

view()->composer(['header', 'footer'],  function($view){
            $view->with('menus', Menu::all());
        });

and everything works great

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question