pass data to inertiajs with view composer in laravel

Viewed 696

Im using Laravel 8 with Jetstream(Inertia stack).

i want to pass data to my Inertia components with view composers.

how do i do that?

i even tried this but doesn't work:

View::composer('*', ProfileComposer::class);

if you want more info here it is:

<?php

namespace App\Providers;

use App\Http\View\Composers\ProfileComposer;
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('*', ProfileComposer::class);
    }
}

and also here is another part:

<?php

namespace App\Http\View\Composers;

use App\Models\Center;
use App\Models\Field;
use Illuminate\View\View;

class ProfileComposer
{
    /**
     * Bind data to the view.
     *
     * @param  \Illuminate\View\View  $view
     * @return void
     */
    public function compose(View $view)
    {
        $view->with('centers', Center::all('id', 'name'))
            ->with('fields', Field::all('id', 'name'));
    }
}

1 Answers

inertia replaces blade views so you should pass data to inertia directly. so if you want for example to share a data to all views you should use: Inertia::share(..)

see: Inertia share

Related