php - Accessing view data inside top level component in Laravel (v8)

one text

Solution:

So, after some work I found a solution by using View Composers. I'll describe what I ended up with in case it helps someone.

Note: A component higher in the hierarchy, like the <x-footer-main /> on my example, it's a view, as much as the final one you're calling via your route/controller.

Created a ViewServiceProvider inside app\Providers

<?php

namespace App\Providers;

use App\Http\View\Composers\DataComposer;
use Illuminate\Support\Facades\View;
use Illuminate\Support\ServiceProvider;

class ViewServiceProvider extends ServiceProvider
{
    /**
     * Register services.
     *
     * @return void
     */
    public function register()
    {
        //
    }

    /**
     * Bootstrap services.
     *
     * @return void
     */
    public function boot()
    {
        View::composer('*', DataComposer::class);
    }
}

Added the provider to the config file. config/app.php

'providers' => [
    /*
                 * Application Service Providers...
    */
    App\Providers\AppServiceProvider::class,
    App\Providers\AuthServiceProvider::class,
    App\Providers\BroadcastServiceProvider::class,
    App\Providers\EventServiceProvider::class,
    App\Providers\RouteServiceProvider::class,
    App\Providers\ViewServiceProvider::class,

],

Created the DataComposer class and the folder structure like app/Http/View/Composers/DataComposer.php

<?php

namespace App\Http\View\Composers;

use Illuminate\View\View;
use App\Models\Data;

class DataComposer
{
    protected $data;

    public function __construct()
    {
        // Dependencies are automatically resolved by the service container...
        $this->data = Data::all();
    }

    public function compose(View $view)
    {
        $view->with('data', $this->data);
    }
}

And it worked!!!

Source