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 modern single-page apps using classic server-side routing and controllers. Provides middleware, helpers, and response rendering to connect Laravel with your Vue/React/Svelte pages while keeping the full Laravel backend workflow.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

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

    Follow the official installation guide for Vite/Webpack setup.

  2. Publish Config:

    php artisan vendor:publish --provider="Inertia\InertiaServiceProvider" --tag=config
    

    This generates config/inertia.php for customization.

  3. First Route/Controller:

    // routes/web.php
    Route::get('/dashboard', function () {
        return Inertia::render('Dashboard');
    });
    
  4. First Vue/React Page:

    <!-- resources/js/Pages/Dashboard.vue -->
    <template>
        <h1>Welcome to Dashboard</h1>
    </template>
    

First Use Case: Rendering a Page

// Controller or route closure
return Inertia::render('Profile', [
    'user' => User::find(1),
    'stats' => $this->getUserStats(), // Custom method
]);

Implementation Patterns

Core Workflows

  1. Page Rendering:

    // Basic render
    return Inertia::render('PageName');
    
    // With props
    return Inertia::render('PageName', ['key' => 'value']);
    
    // With shared data (via middleware)
    Inertia::share(['auth' => fn() => Auth::user()]);
    
  2. Navigation:

    // Redirect with inertia
    return redirect()->route('dashboard')->withInertia([
        'message' => 'Success!'
    ]);
    
    // Link in Vue
    <Link href="/dashboard">Go to Dashboard</Link>
    
  3. Deferred Props (for lazy-loading):

    // In controller
    return Inertia::render('Page', [
        'user' => User::find(1),
        'posts' => Post::query()->take(10)->get(),
        'deferred' => fn() => Post::query()->skip(10)->get(),
    ]);
    
    // In Vue
    <template>
        <div @inertia-preload="posts">
            <!-- Render posts -->
        </div>
    </template>
    

Integration Tips

  1. Middleware:

    // HandleInertiaRequests middleware (auto-included)
    // Custom middleware for shared data
    public function share(Request $request): array
    {
        return [
            'appName' => config('app.name'),
        ];
    }
    
  2. Testing:

    // Test response assertions
    $response->assertInertia(fn (AssertableInertia $page) =>
        $page->component('Dashboard')
             ->has('user', fn ($user) => $user['name'] === 'John')
    );
    
  3. SSR (Server-Side Rendering):

    // Check SSR health
    if (!Inertia::isHealthy()) {
        abort(503);
    }
    
    // SSR-specific rendering
    return Inertia::render('Page', [], false, [
        'ssr' => true,
    ]);
    
  4. Flash Data:

    // Set flash data
    return redirect()->route('dashboard')->withInertiaFlash([
        'success' => 'Operation completed!',
    ]);
    
    // Access in Vue
    <template>
        <div v-if="$page.props.flash.success">
            {{ $page.props.flash.success }}
        </div>
    </template>
    
  5. Custom URL Resolution:

    // config/inertia.php
    'url' => [
        'resolver' => App\Services\CustomUrlResolver::class,
    ],
    

Gotchas and Tips

Common Pitfalls

  1. Missing Shared Data:

    • Ensure shared data is set in middleware (HandleInertiaRequests) or via Inertia::share().
    • Fix: Add to app/Http/Middleware/HandleInertiaRequests.php:
      public function share(Request $request): array
      {
          return array_merge(parent::share($request), [
              'key' => 'value',
          ]);
      }
      
  2. Deferred Props Not Loading:

    • Forgetting @inertia-preload or incorrect prop names.
    • Fix: Verify prop names match exactly (case-sensitive) and use:
      <div @inertia-preload="deferredPropName">
          <!-- Content -->
      </div>
      
  3. Flash Data Persistence:

    • Flash data may not persist across redirects if not using withInertiaFlash().
    • Fix: Use withInertiaFlash() instead of Laravel’s with():
      return redirect()->route('dashboard')->withInertiaFlash(['error' => 'Failed']);
      
  4. SSR Issues:

    • Missing Vite manifest or bundle during SSR.
    • Fix: Run php artisan inertia:check-ssr or ensure ssr.ensure_bundle_exists is configured.
  5. Prop Modifiers Ignored:

    • Using once() or reload() modifiers incorrectly.
    • Fix: Use Inertia::merge() or Inertia::scroll():
      return Inertia::render('Page', [], false, [
          'merge' => ['key' => 'value'],
          'scroll' => ['x' => 0, 'y' => 0],
      ]);
      

Debugging Tips

  1. Inspect Props:

    • Use dd($page->props) in Vue’s created() lifecycle to debug props.
  2. Check SSR:

    • Run php artisan inertia:check-ssr to verify SSR setup.
  3. Middleware Debugging:

    • Temporarily add dd($this->share($request)) to HandleInertiaRequests to inspect shared data.
  4. Network Tab:

    • Inspect the X-Inertia: true header in the response to confirm Inertia is working.

Extension Points

  1. Custom Prop Providers:

    • Implement ProvidesInertiaProps interface for reusable prop logic:
      class UserProvider implements ProvidesInertiaProps
      {
          public function getProps(Request $request): array
          {
              return ['user' => Auth::user()];
          }
      }
      
    • Register in HandleInertiaRequests:
      public function share(Request $request): array
      {
          return array_merge(parent::share($request), [
              'user' => (new UserProvider())->getProps($request),
          ]);
      }
      
  2. Custom URL Resolver:

    • Extend Inertia\Routing\UrlResolver for dynamic URL generation:
      class CustomUrlResolver extends UrlResolver
      {
          public function resolve(string $page): string
          {
              // Custom logic
              return parent::resolve($page);
          }
      }
      
    • Configure in config/inertia.php:
      'url' => [
          'resolver' => App\Services\CustomUrlResolver::class,
      ],
      
  3. Testing Helpers:

    • Use AssertableInertia for complex assertions:
      $response->assertInertia(fn (AssertableInertia $page) =>
          $page->component('Dashboard')
               ->has('user.id', 1)
               ->missing('deletedUser')
      );
      
  4. Partial Requests:

    • For SPAs, use partial requests to update data without full page reloads:
      // In Vue
      <template>
          <div @inertia-preload="posts">
              <button @click="$inertia.partial('posts', { page: 2 })">Load More</button>
          </div>
      </template>
      
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.
davejamesmiller/laravel-breadcrumbs
artisanry/parsedown
christhompsontldr/phpsdk
enqueue/dsn
bunny/bunny
enqueue/test
enqueue/null
enqueue/amqp-tools
milesj/emojibase
bower-asset/punycode
bower-asset/inputmask
bower-asset/jquery
bower-asset/yii2-pjax
laravel/nova
spatie/laravel-mailcoach
spatie/laravel-superseeder
laravel/liferaft
nst/json-test-suite
danielmiessler/sec-lists
jackalope/jackalope-transport