Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I use a controller for a "partial" view in Laravel?

Here is my situation. I have a layout.blade.php which most of my pages use. Within this file, I have some partial pieces that I include, like @include('partials.header'). I am trying to use a controller to send data to my header.blade.php file, but I'm confused as to exactly how this will work since it is included in every view that extends layout.blade.php.

What I am trying to do is retrieve a record in my database of any Game that has a date of today's date, if it exists, and display the details using blade within the header.

How can I make this work?

like image 511
develpr Avatar asked May 07 '17 00:05

develpr


2 Answers

I think to define those Game as globally shared is way to go.

In your AppServiceProvider boot method

public function boot()
{

    view()->composer('partials.header', function ($view) {
        view()->share('todayGames', \App\Game::whereDay('created_at', date('d')->get());
    });

    // or event view()->composer('*', Closure) to share $todayGames accross whole blade
}

Render your blade as usual, partial.header blade

@foreach ($todayGames as $game)
  // dostuffs
@endforeach
like image 73
Chay22 Avatar answered Oct 23 '22 00:10

Chay22


In Laravel you can create a service class method that acts like a controller and use @inject directive to access this in your partial view. This means you do not need to create global variables in boot(), or pass variables into every controller, or pass through the base view layout.blade.php.

resources/views/header.blade.php:
@inject('gamesToday', 'App\Services\GamesTodayService')
@foreach ($gamesToday->getTodayGames() as $game)
  // display game details
@endforeach
like image 1
Richard F Avatar answered Oct 22 '22 23:10

Richard F