B
B
BonBon Slick2017-06-19 20:24:51
Laravel
BonBon Slick, 2017-06-19 20:24:51

How to pass $user variable to ViewComposer?

In this example, the variable is passed through the controller, in only one function. https://stackoverflow.com/questions/34153072/larav... But then ViewComposer makes sense. There is a $user variable, which is passed with the transition to the user's profile. It is dynamic, the user is transferred in the route, to whom the yurl, that and the user model. it is necessary to render a variable for each user, since their data is different. Simply sharing the data will not work, you need to somehow pass a variable, which user should be processed before loading the view.
Example: a user has a rating. The rating is displayed in the user profile layout. This layout loads a lot of views, each time in the controller functions it is cumbersome to count, even if taken out into a separate function, extra code comes out. In ViewComposer, this can be organized at once, if you pass there a user variable for which we will display the rating.
Example, passing a static variable https://laravel.com/docs/5.4/views#view-composers
How to pass?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
B
BonBon Slick, 2017-06-19
@BonBonSlick

We receive parameters through the facade:

use Route;
...
  public function __construct()
    {
dd(Request::segments());
 dd(request()->route()->parameters);
dd(Route::current()->parameters());
dd(Route::getCurrentRoute()->parameters());

The 3rd option is for Lara 5+, in the 4th only the 2nd one works.
We get a parameter, if everything is built correctly for you, model binding by route, then you should get this:
array:1 [▼
  "user" => User {#488 ▶}
]

ps more details https://laravel.com/api/5.0/Illuminate/Routing/Rout...

A
Alexander Aksentiev, 2017-06-19
@Sanasol

the user has a rating

Well, as if it is obvious that this should be done in the user model, and displayed anywhere as many times as you like.
Why is it considered in the controller.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question