Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel Jetstream Inertia Shared Global App Data

I want to share something I figured out since there's not much info out there (that I couldn't find). Laravel 8 with Jetstream Inertia has a few shared objects, like user, current route... You can access them in your components using the $page variable. I needed to add a menu array as a global variable but could not figure it out, even after finding some info on the the official Inertia documentation. It's just different in Laravel Jetstream.

It wasn't until I found Laravel Jetstream's middleware for shared data (ShareInertiaData) that I figured out how to do it.

Here's it is:

  1. Create a middleware in the app/Http/Middleware.php. I called mine ShareInertiaCustomData.
<?php

namespace App\Http\Middleware;

use Inertia\Inertia;

class ShareInertiaCustomData
{
    public function handle($request, $next)
    {
        Inertia::share([
            'menu' => config('menu'),
        ]);

        return $next($request);
    }
}
  1. Place it in the app/Http/Kernel.php
    protected $middlewareGroups = [
        'web' => [
            ...
            \App\Http\Middleware\ShareInertiaCustomData::class,
        ],
    ];

I hope that helps and no one else will have to spend hours trying to figure this out.

like image 360
phoenix Avatar asked Nov 15 '20 19:11

phoenix


2 Answers

Thanks for sharing this! While going through your steps I identified the class \App\Http\Middleware\HandleInertiaRequests, which is the right place to enter own page props. You may use the "share" method to add your properties. This is also explained in the Inertia documentation about Shared Data. Please see an example below.

/**
 * Defines the props that are shared by default.
 *
 * @see https://inertiajs.com/shared-data
 * @param  \Illuminate\Http\Request  $request
 * @return array
 */
public function share(Request $request)
{
    return array_merge(parent::share($request), [
        'current_topic' => Auth::user() ? Auth::user()->currentTeam->currentTopic : null
    ]);
}

}

like image 88
Marco Avatar answered Nov 11 '22 03:11

Marco


Thanks to the guys at the official Discord channel, I found out that I had the same problem because I had an older version of the inertia-laravel package which didn't include a share function.

Make sure you use at least v0.3.0 where it is included.

like image 42
Ben Horvath Avatar answered Nov 11 '22 02:11

Ben Horvath