Please help me, i want to share my data from the database to the child blade component and also return the views of the component.
I’m using layouts with @yield in my parent layout.
<body>
@include('Layout.topbar') // this the component that i want to share with the data from the database
@include('Layout.navbar')
@yield('content') // this the views that i want to return
@include('Layout.footer')
</body>
This is my contoller look like:
$carouselImages = CarouselImage::active()->get();
$newsActivities = NewsActivities::active()->get();
$contact = Contact::all(); // this the data that i want to share to the topbar.blade.php
view()->share('contacts', $contact); // this work, but after navigate to the other page, it's show an errors about the $contacts undefined.
return view('Home.isi', [
'carouselImages' => $carouselImages,
'newsActivities' => $newsActivities
]);
i’d tried to find that simple trick, but i can’t find the right one.
Please help ~
2
Answers
You can consider putting it in boot method of a provider, such as AppServiceProvider:
For the better performance, you can put contacts in cache and then retrieve it from cache.
Better not make database or cache queries in a boot method of a service provider. This code will be executed for every request, even for post requests.
As far as I understand:
Home.isi
is returned in a controller (will be injected with the yield) where you fetch the contacts to share.Did I understand correctly? If this is the case I think view composers are the best fit for you: https://laravel.com/docs/10.x/views#view-composers
You can register those for different views, like for
Layout.topbar
. And everytime the topbar is rendered you can add the data.