Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Inertia Laravel Laravel Package

inertiajs/inertia-laravel

Laravel adapter for Inertia.js: build single-page apps using classic server-side routing and controllers. Provides middleware, helpers, and response macros to render Inertia pages, share props, handle versioning, and integrate seamlessly with Laravel.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require inertiajs/inertia-laravel
    npm install @inertiajs/inertia @inertiajs/inertia-laravel
    

    Run migrations:

    php artisan inertia:middleware
    
  2. Configure app/Http/Kernel.php: Add Inertia middleware to $middlewareGroups['web']:

    \Inertia\Middleware::class,
    
  3. First Route/Controller:

    Route::get('/dashboard', function () {
        return Inertia::render('Dashboard', [
            'users' => User::all(),
        ]);
    });
    
  4. Create Vue/React Component:

    <!-- resources/js/Pages/Dashboard.vue -->
    <template>
        <div>
            <h1>Dashboard</h1>
            <ul>
                <li v-for="user in users" :key="user.id">
                    {{ user.name }}
                </li>
            </ul>
        </div>
    </template>
    
    <script>
    export default {
        props: {
            users: Array,
        },
    };
    </script>
    
  5. Build Assets:

    npm run dev
    

First Use Case: CRUD Page

// resources/js/Pages/Posts/Index.vue
export default {
    props: {
        posts: Array,
        errors: Object,
    },
};
// routes/web.php
Route::get('/posts', [PostController::class, 'index']);
Route::post('/posts', [PostController::class, 'store']);
// app/Http/Controllers/PostController.php
public function index() {
    return Inertia::render('Posts/Index', [
        'posts' => Post::latest()->get(),
    ]);
}

public function store(Request $request) {
    $validated = $request->validate([
        'title' => 'required|string|max:255',
    ]);

    Post::create($validated);

    return redirect()->route('posts.index');
}

Implementation Patterns

Core Workflows

1. Page Rendering

  • Basic Rendering:
    return Inertia::render('PageName', ['prop' => $value]);
    
  • Shared Props (via middleware):
    public function share(Request $request): array
    {
        return [
            'auth' => [
                'user' => $request->user(),
            ],
            'settings' => [
                'theme' => 'dark',
            ],
        ];
    }
    

2. Deferred Props

  • Lazy-load data:
    return Inertia::render('Page', [
        'users' => User::all(),
        'deferred' => fn() => [
            'stats' => Stats::calculate(),
        ],
    ]);
    
  • Client-side fetch:
    <script setup>
    const { data: stats } = await useFetch('/api/stats');
    </script>
    

3. Form Handling

  • Validation Errors:
    return Inertia::render('FormPage', [
        'errors' => $validator->errors(),
    ]);
    
  • Flash Messages:
    return redirect()->route('dashboard')->with([
        'message' => 'Post created!',
    ]);
    

4. Navigation

  • Redirects:
    return redirect()->route('posts.index');
    
  • Inertia Links (Vue):
    <Link href="/posts">Posts</Link>
    

5. SSR Optimization

  • Disable SSR for specific pages:
    Inertia::disableSsr();
    return Inertia::render('NonSSRPage');
    
  • SSR Runtime Config:
    config(['inertia.ssr.runtime' => 'edge']);
    

Integration Tips

Laravel Features

  • Authentication:
    return Inertia::render('Dashboard', [
        'user' => Auth::user(),
    ]);
    
  • Policies:
    if (Gate::denies('view-post', $post)) {
        abort(403);
    }
    
  • Events:
    event(new PostCreated($post));
    return Inertia::render('Posts/Index', ['posts' => Post::latest()->get()]);
    

Testing

  • Assertions:
    $response = $this->get('/dashboard');
    $response->assertInertia(fn (AssertableInertia $page) => $page
        ->component('Dashboard')
        ->has('users', 3)
    );
    
  • Deferred Props:
    $response->assertInertia(fn (AssertableInertia $page) =>
        $page->loadDeferredProps(fn (AssertableInertia $page) =>
            $page->has('stats', ['visitors' => 100])
        )
    );
    

Performance

  • Prop Modifiers:
    return Inertia::render('Page', [
        'users' => User::all()->toArray(),
        'posts' => Post::all()->only(['id', 'title']),
    ]);
    
  • Once Props (client-side only):
    return Inertia::render('Page', [
        'once' => fn() => ['data' => 'persists'],
    ]);
    

Advanced Patterns

  • Dynamic Imports:
    <script setup>
    const { data: component } = await useAsyncComponent(() =>
        import(`./Components/${dynamicComponent}.vue`)
    );
    </script>
    
  • Shared State:
    // app/Providers/InertiaServiceProvider.php
    public function share(Request $request): array
    {
        return [
            'app' => [
                'name' => config('app.name'),
            ],
        ];
    }
    

Gotchas and Tips

Pitfalls

  1. Middleware Priority:

    • Inertia middleware must be placed after Authenticate but before VerifyCsrfToken in $middlewareGroups['web'].
    • Fix: Reorder middleware in app/Http/Kernel.php.
  2. Deferred Props Caching:

    • Deferred props are not cached by default. Use rescue to handle failures:
      'deferred' => fn() => [
          'stats' => Stats::calculate()->rescue(fn() => null),
      ],
      
  3. Flash Data Loss:

    • Flash data is not preserved across Inertia redirects unless using Inertia::location() or Inertia::redirect().
    • Fix: Use Laravel's with() or session()->flash().
  4. SSR Mismatches:

    • Ensure SSR and client-side bundles are in sync. Mismatches cause hydration errors.
    • Fix: Run npm run dev or npm run build after changes.
  5. Prop Type Mismatches:

    • Inertia expects props to match exactly between server and client. Avoid dynamic types (e.g., mixing null and false).
  6. Middleware Conflicts:

    • Global middleware (e.g., TrimStrings) may interfere with Inertia's request handling.
    • Fix: Wrap Inertia-specific logic in if (! request()->expectsJson()).
  7. Testing Quirks:

    • assertInertia() requires exact component names (case-sensitive).
    • Fix: Use ->component('Exact/Case/Name').

Debugging Tips

  1. Log Props:

    \Log::info('Inertia props:', [
        'page' => Inertia::current()->page,
        'props' => Inertia::current()->props,
    ]);
    
  2. Check SSR Health:

    php artisan inertia:check-ssr
    
    • Fixes: Ensure NODE_ENV=production and assets are built.
  3. Inspect Deferred Props:

    $deferred = Inertia::current()->deferred;
    \Log::debug('Deferred props:', $deferred);
    
  4. Hydration Errors:

    • Enable Vue's devtools to inspect mismatched props.
    • Fix: Ensure server props match client component props exactly.
  5. Middleware Debugging:

    • Temporarily disable middleware to isolate issues:
      // app/Http/Kernel.php
      protected $middleware = [
          // \App\Http\Middleware\TrimStrings::class, // Disable temporarily
      ];
      

Extension Points

  1. Custom Prop Modifiers:

    // app/Providers/InertiaServiceProvider.php
    public function modifyProps($props, $page)
    {
        if ($page === 'Dashboard') {
            $props['formattedDate'] = now()->format('Y-m-d');
        }
        return $props;
    }
    
  2. **

Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle
atriumphp/atrium
sandermuller/package-boost-laravel
sandermuller/boost-skills
redaxo/core
yusufgenc/filament-api-forge
l3aro/rating-star-for-filament
leek/filament-subtenant-scope
anil/file-picker
broqit/fields-ai