Laravel - How to pass data to include
Asked Answered
S

3

15

So essentially all of my views are using the header.blade.php since I am including it in my master layout. I need to pass data to the header on every single view. Is there a way to pass data just to the include rather than passing the data for the header in each view?

Synergy answered 6/5, 2016 at 15:12 Comment(0)
W
5

One option if you're trying to send data only to the included view is to use a view composer. They will fire even in the case of trying to prepare a view for @include

view()->composer('header', function($view) {
    $view->with('data', 'some data');
});
Walke answered 6/5, 2016 at 15:25 Comment(1)
I found a solution by following the link and looking into "Sharing Data With All Views". Thanks!Synergy
S
50

You don't need to do that, but you can:

All variables that are available to the parent view will be made available to the included view. Even though the included view will inherit all data available in the parent view, you may also pass an array of extra data to the included view:

@include('view.name', ['some' => 'data'])
Spritsail answered 6/5, 2016 at 15:14 Comment(3)
this is the correct answer! but the question isn't enough related to the subject!Neptunium
is it locally scoped to that '@include' and its descendants?Goddess
@Alexey I tried doing this and I am able to print the value of the {{$data}} being passed but when trying to pass it to a route it is not being recognized.Erasure
W
5

One option if you're trying to send data only to the included view is to use a view composer. They will fire even in the case of trying to prepare a view for @include

view()->composer('header', function($view) {
    $view->with('data', 'some data');
});
Walke answered 6/5, 2016 at 15:25 Comment(1)
I found a solution by following the link and looking into "Sharing Data With All Views". Thanks!Synergy
T
1

actually the very best and faster method of sharing data to all views could be just using the

      AppServiceProvider

instead of Jeff's answer you can use the share method instead of the composer method and achieve your goal faster.

Just pass the data you want in the boot method of the AppServiceProvider like following

      public function boot()
{
    View::share('key', 'value');
}

for more check this

Trunk answered 18/6, 2020 at 4:28 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.