Add a controller and page component to an Inertia + Svelte + Laravel app

Official docs version: https://inertiajs.com/client-side-setup

Inertia.js enables us to use a frontend framework (Svelte, Laravel, Vue) in a Laravel app with access to data from the controller, just like the default Blade view.

Steps:

  1. Server-side (Laravel controller) — return Inertia view instead of the default view
  2. Client-side (Svelte component) — access controller data as props
    • I use Svelte in this example; the workflow is similar for React or Vue.

1) Return Inertia view from Laravel Controller

// app/Http/Controllers/SomeController.php
 
use Inertia\Inertia;
 
class SomeController extends Controller
{
  public function index() {
    // without data
    return Inertia::render("pages/MySveltePage"); 
    // with data
    return Inertia::render("pages/MySveltePage", ["foo" => "bar"]);
  }
}

Difference with regular Blade view:

- return view("pages.my_blade_page", $someData);
+ return Inertia::render("pages/MySveltePage", $someData);

2) Add Svelte page component

Create a file in pages/MySveltePage.svelte:

<script>
  export let foo;
</script>
 
<h1 class="text-3xl font-bold mb-4">{foo}</h1>
<p>This is a Svelte component rendered with Inertia</p>

We can access global props from the HandleInertiaRequests middleware in the $page store, along with other Inertia-related data.

import { page } from "@inertiajs/inertia-svelte";

We can use Laravel's server side functionalities (eg. user login in session), pass it as a global prop, and access it from our client-side component.

<script>
  import { page } from "@inertiajs/inertia-svelte";
</script>
 
{#if $page.props.user}
  <p>
    Hello {$page.props.user.username} | <a href="/logout">logout</a>
  </p>
{:else}
  <p>Hello guest</p>
{/if}

In:

Links to this note

  • Est ex deserunt esse ut pariatur quis fugiat id velit commodo

    Ut anim fugiat laboris et eiusmod aliquip.

  • Est ex deserunt esse ut pariatur quis fugiat id velit commodo

    Ut anim fugiat laboris et eiusmod aliquip.

  • Est ex deserunt esse ut pariatur quis fugiat id velit commodo

    Ut anim fugiat laboris et eiusmod aliquip.

  • Est ex deserunt esse ut pariatur quis fugiat id velit commodo

    Ut anim fugiat laboris et eiusmod aliquip.

  • Est ex deserunt esse ut pariatur quis fugiat id velit commodo

    Ut anim fugiat laboris et eiusmod aliquip.

  • Est ex deserunt esse ut pariatur quis fugiat id velit commodo

    Ut anim fugiat laboris et eiusmod aliquip.

  • Est ex deserunt esse ut pariatur quis fugiat id velit commodo

    Ut anim fugiat laboris et eiusmod aliquip.