Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

timsims's avatar

how to pass shared data to every page

Consider a website for products, where users can browse a product list (ProductList Page) and view product details (ProductView Page). On every page, there are product categories (data retrieved from the database) that users can click on to filter products in that category.

In a traditional backend/frontend separated design, there would be a dedicated API for categories.

With Inertia, I am wondering how to pass the categories (and all other shared data) to the page. It wouldn't make sense to pass it from every controller.

0 likes
2 replies
LaryAI's avatar
Level 58

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:

  1. 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);
        }
    }
    
  2. Register the Middleware: Register the middleware in your app/Http/Kernel.php file so that it runs on every request.

    // app/Http/Kernel.php
    
    protected $middlewareGroups = [
        'web' => [
            // Other middleware...
            \App\Http\Middleware\ShareCategories::class,
        ],
    ];
    
  3. Access Shared Data in Your Inertia Pages: Now, you can access the shared categories data 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.

Please or to participate in this conversation.