To pass shared data to every page in an Inertia.js application, you can use Inertia's shared data feature. This allows you to define data that should be available to all your Inertia responses, without having to manually pass it from every controller.
Here's how you can achieve this:
-
Create a Middleware to Share Data: Create a middleware that will share the categories data with all Inertia responses.
// app/Http/Middleware/ShareCategories.php namespace App\Http\Middleware; use Closure; use Inertia\Inertia; use App\Models\Category; class ShareCategories { /** * Handle an incoming request. * * @param \Illuminate\Http\Request $request * @param \Closure $next * @return mixed */ public function handle($request, Closure $next) { // Fetch categories from the database $categories = Category::all(); // Share categories with Inertia Inertia::share('categories', $categories); return $next($request); } } -
Register the Middleware: Register the middleware in your
app/Http/Kernel.phpfile so that it runs on every request.// app/Http/Kernel.php protected $middlewareGroups = [ 'web' => [ // Other middleware... \App\Http\Middleware\ShareCategories::class, ], ]; -
Access Shared Data in Your Inertia Pages: Now, you can access the shared
categoriesdata in any of your Inertia pages. For example, in a Vue component:<template> <div> <h1>Product Categories</h1> <ul> <li v-for="category in categories" :key="category.id"> {{ category.name }} </li> </ul> </div> </template> <script> export default { props: { categories: Array, }, } </script>
By following these steps, you ensure that the categories data is available on every page without having to pass it explicitly from each controller. This approach keeps your controllers clean and your shared data management centralized.