6

Currently we are using the Laravel framework on several projects, but one issue we keep running into which i don't like is the following issue:

Lets say you have a Homepage and a Content page

HomepageController has all Homepage specific php code ContentpageController has all Content specific php code

we have an app.blade.php that does

@yield('page')

HomepageController calls the view homepage.blade.php containing

@extends('app')

@section('page')
     Some HTML part
     @include('parts.top_5')
@endsection

ContentController calls the view content.blade.php containing

@extends('app')

@section('page')
     Some different HTML part
     @include('parts.top_5')
@endsection

Here you can see both pages include parts.top_5, the top 5 needs some specific variables to output the top5. Now the issue is we are currently copying the code for the top5 variables in both controllers or in grouped middleware but is there a better solution to generate some blade specific variables when the part is included? So a bit like running a controller function on loading the blade template?

I have been searching the internet but can't seem to find anyone with the same question. Hopefully someone can help me on this mindbreaking issue!

RemcoDN
  • 143
  • 10
  • I'm not that good with english but do you mean you want to pass data to the view via @include if so try this @include('view.name', ['data' => 'yourdata'])? – xenish May 22 '15 at 12:02

1 Answers1

2

You can add this binding to AppServiceProvider

(or any custom ServiceProvider You want)

like this:

public function boot()
{
    $view->composer('parts.top_5', function($view) {
        $view->with('any_data' => 'You want');
    })
}

This way any time Laravel will compose parts.top_5 view this closure method will be triggerd.

And in documentations it's here: http://laravel.com/docs/5.0/views#view-composers

D. Cichowski
  • 777
  • 2
  • 7
  • 24
  • Just Googled when you didn't post the link but found the same page, now i can see Laraval did add this in the v5.0 documentation, very cool going to try this out seems to be exactly what i need. – RemcoDN May 22 '15 at 12:17