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?
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With