skip to Main Content

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


  1. You can consider putting it in boot method of a provider, such as AppServiceProvider:

    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        $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.
    }
    

    For the better performance, you can put contacts in cache and then retrieve it from cache.

    Login or Signup to reply.
  2. 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:

    • You have a topbar, navbar and a footer. In between you yield the content of your page
    • The view Home.isi is returned in a controller (will be injected with the yield) where you fetch the contacts to share.
    • You want however, that the Topbar has always access to the contacts.

    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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search