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

Official Laravel adapter for Inertia.js. Build modern single-page apps using classic server-side routing and controllers, without building an API. Provides Inertia responses, shared props, middleware helpers, and integration with Laravel features.

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 and publish config:

    php artisan inertia:install
    
  2. First Page Render: In a controller, use the Inertia::render() facade:

    use Inertia\Inertia;
    
    public function show()
    {
        return Inertia::render('Dashboard', [
            'users' => User::all(),
        ]);
    }
    
  3. First Vue/React Component: Create a file at 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>
    
  4. Route Configuration:

    Route::get('/dashboard', [DashboardController::class, 'show'])
        ->middleware(['auth', 'verified']);
    

Key First Use Case

Server-Side Data Fetching:

// Controller
return Inertia::render('Posts/Index', [
    'posts' => Post::with('author')->latest()->get(),
    'filters' => request()->only(['search', 'category']),
]);
<!-- Posts/Index.vue -->
<script>
export default {
    props: {
        posts: Array,
        filters: Object,
    }
}
</script>

Implementation Patterns

Core Workflows

  1. Page Rendering Patterns:

    • Basic Rendering:
      return Inertia::render('PageName', ['prop1' => $value1]);
      
    • Shared Data:
      // In AppServiceProvider boot()
      Inertia::share([
          'auth' => fn () => [
              'user' => Auth::user(),
          ],
      ]);
      
  2. Navigation & Redirects:

    • Client-Side Navigation:
      <Link href="/dashboard">Dashboard</Link>
      
    • Server-Side Redirects:
      return redirect()->route('dashboard')->withInertiaFlash([
          'message' => 'Success!',
      ]);
      
  3. Data Loading Strategies:

    • Eager Loading:
      return Inertia::render('Profile', [
          'user' => User::with('posts', 'comments')->find($id),
      ]);
      
    • Deferred Props (for lazy loading):
      return Inertia::render('Posts/Index', [
          'posts' => Post::all(),
          'comments' => fn () => Comment::whereIn('post_id', $postIds)->get(),
      ]);
      
      <script>
      export default {
          props: {
              posts: Array,
              comments: { default: () => [] },
          },
          async created() {
              await this.$inertia.partial(this.$page.props.comments);
          }
      }
      </script>
      
  4. Component-Based Architecture:

    • Nested Pages:
      // Parent page
      return Inertia::render('Layout', [
          'child' => Inertia::render('ChildComponent', ['data' => $data]),
      ]);
      
    • Partial Updates:
      return Inertia::location('/dashboard', [
          'partials' => [
              'stats' => Inertia::render('StatsCard', ['data' => $newData]),
          ],
      ]);
      

Integration Tips

  1. Authentication:

    // In App\Http\Middleware\HandleInertiaRequests
    public function root()
    {
        return Inertia::root(fn () => match (Auth::user()) {
            null => 'Login',
            default => 'Dashboard',
        });
    }
    
  2. Form Handling:

    // Controller
    public function store(Request $request)
    {
        $validated = $request->validate([...]);
        $post = Post::create($validated);
    
        return redirect()->route('posts.show', $post)
            ->withInertiaFlash([
                'success' => 'Post created!',
            ]);
    }
    
    <!-- PostCreate.vue -->
    <script>
    export default {
        props: {
            errors: Object,
            flash: Object,
        }
    }
    </script>
    
  3. API Integration:

    // Controller
    public function getData()
    {
        $response = Http::get('https://api.example.com/data');
        return Inertia::render('DataPage', [
            'apiData' => $response->json(),
        ]);
    }
    
  4. Testing:

    // Test
    $response = $this->get('/dashboard');
    $response->assertInertia(fn (AssertableInertia $page) => $page
        ->component('Dashboard')
        ->has('users', 3)
    );
    

Gotchas and Tips

Common Pitfalls

  1. Middleware Priority:

    • Ensure HandleInertiaRequests middleware is registered after authentication middleware:
      // kernel.php
      'web' => [
          \App\Http\Middleware\Authenticate::class,
          \Inertia\Middleware::class, // <-- After auth
      ],
      
  2. Shared Data Timing:

    • Shared data is resolved after middleware runs. For auth data:
      Inertia::share([
          'auth' => fn () => [
              'user' => Auth::user(),
              'can' => fn (string $ability) => Auth::user()->can($ability),
          ],
      ]);
      
  3. Deferred Props:

    • Gotcha: Deferred props must be callables (not strings):
      // Wrong (string)
      'comments' => 'App\Http\Controllers\CommentController@getComments',
      
      // Correct (callable)
      'comments' => fn () => Comment::all(),
      
    • Tip: Use rescue() for error handling:
      'comments' => fn () => Comment::all()->rescue(fn () => []),
      
  4. Flash Data:

    • Gotcha: Flash data persists through one redirect only. For multi-step processes:
      session()->flash('temp_data', $data);
      
    • Tip: Use withInertiaFlash() for Inertia-specific flash messages.
  5. SSR (Server-Side Rendering):

    • Gotcha: SSR requires a compiled Vue/React bundle. For development:
      npm run dev
      
    • Tip: Disable SSR temporarily:
      Inertia::disableSsr();
      

Debugging Tips

  1. Inspect Page Props:

    // In middleware or controller
    \Log::info('Page props:', [
        'props' => $request->inertia()->props,
        'url' => $request->url(),
    ]);
    
  2. Check Deferred Props:

    // In controller
    $deferred = $request->inertia()->deferred;
    \Log::info('Deferred props:', $deferred);
    
  3. Middleware Debugging:

    • Use dd($request->inertia()) to inspect the Inertia request object.
  4. Vue/React DevTools:

    • Inspect the $page object in browser console to see all props and partials.

Extension Points

  1. Custom Page Transforms:

    // In AppServiceProvider
    Inertia::pageTransform(function (Page $page) {
        if ($page->component === 'Dashboard') {
            $page->with([
                'extraData' => fn () => Cache::get('dashboard_extra'),
            ]);
        }
        return $page;
    });
    
  2. Custom Inertia Responses:

    // In AppServiceProvider
    Inertia::macro('customResponse', function ($component, $props = []) {
        return response()->inertia($component, $props, 200, [
            'X-Custom-Header' => 'value',
        ]);
    });
    
  3. Middleware Hooks:

    // In HandleInertiaRequests middleware
    public function share(Request $request): array
    {
        return array_merge(parent::share($request), [
            'requestData' => $request->only(['search', 'page']),
        ]);
    }
    
  4. Testing Helpers:

    // In TestCase
    use function Inertia\Testing\AssertableInertia;
    
    public function assertInertiaPage(AssertableInertia $page, string $component, array $props = [])
    {
        $page->component($component);
        foreach
    
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.
codraw/framework-extra-bundle
codraw/messenger
codraw/security
codraw/mailer
codraw/contracts
codraw/profiling
codraw/dependency-injection
codraw/tester
codraw/core
nexmo/api-specification
capell-app/block-library
axium/identity
cetria/laravel-dummy-models
cetria/reflection-helper
agropredict/sso-auth-bundle
evolvestudio/spam-protection
datacore/hub-sdk
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony