Laravel将变量偏离视图部分到主刀片或部分之间

I have a Laravel 5.5 app that uses view blades conventionally, nothing fancy. My blade is a long table of data and I split the group sections (item categories) into their own partials to manage the code better.

However, I can't find a way to pass variable data from the partials back to the main blade, or even between partials. The scope of the variables are bound within the partials and I need to show a page total that aggregates the sub-totals from the various partials (sections). I did try using

View::share('portfolio_total', 100);

in the AppServiceProvider, to no avail. I can set a value (like the 100 shown) that stays intact in the master blade, but doesn't pick up the value set in that variable in the partial. Changing the variable value inside the partial doesn't update the value available to the master blade. I've searched extensively for this and there are many examples of passing values into partials, but not back out.

Is there a Laravel trick for defining the equivalent of global variables that can have their value set in an included partial blade, and carry that value to another partial blade, or out to the master blade?

Thanks in advance.

I can't find a way to pass variable data from the partials back to the main blade, or even between partials.

That is because this is absolute bad practice. Hence the framework does not allow that (without abuses).

Why?

In the MVC world (which Laravel implements), views are responsible for displaying data.

If you are computing anything in your views (partials or not), then it means you are giving Views the responsibility of the Controller and/or Model. Which is not good of course.

Then what?

Idea is to compute everything you need before using the views. Two options:

  • If your view/partial is used only by a single controller method, simply pass the data to the view as usual.
  • If your view/partial is used in various places, setup a ViewComposer which will be able to pass the computed data each time that partial is used.

What usually I do is the following.

On my controller, to return data I do this:

    $data = [];
    $data['dummyData'] = Dummy::all();
    $data['extraData'] = 'Extra string';
    return view('myroute.index', array('data' => $data));

Then on each of my views (The view and the partials)

@php
  $dummy = $data['dummyData'];
  $extra = $data['extraData'];
@endphp

And then I can use the variable in the blade as any other: {{ $extra }}