### Install Vue Dependencies Source: https://inertiajs.com/docs/v2/installation/client-side-setup Install Vue and its Vite plugin using npm. Ensure these are installed before proceeding with Inertia setup. ```bash npm install vue @vitejs/plugin-vue ``` -------------------------------- ### Install Inertia dependencies Source: https://inertiajs.com/docs/v2/installation/client-side-setup Install the required client-side adapter for your specific framework. ```bash npm install @inertiajs/vue3 ``` ```bash npm install @inertiajs/react ``` ```bash npm install @inertiajs/svelte ``` -------------------------------- ### Install Inertia.js v2.0 client-side adapters Source: https://inertiajs.com/docs/v2/getting-started/upgrade-guide Use npm to install the appropriate client-side adapter for your framework. ```bash npm install @inertiajs/vue3@^2.0 ``` ```bash npm install @inertiajs/react@^2.0 ``` ```bash npm install @inertiajs/svelte@^2.0 ``` -------------------------------- ### Install NProgress Library Source: https://inertiajs.com/docs/v2/advanced/progress-indicators Install the NProgress library using npm. ```bash npm install nprogress ``` -------------------------------- ### Start Progress Bar on Visit Start Source: https://inertiajs.com/docs/v2/advanced/progress-indicators Use the 'start' event listener on the Inertia router to begin the NProgress bar when a new visit starts. ```javascript router.on('start', () => NProgress.start()) ``` -------------------------------- ### Initialize the Inertia app Source: https://inertiajs.com/docs/v2/installation/client-side-setup Boot the Inertia application in your main JavaScript file using the framework-specific setup. ```js import { createApp, h } from 'vue' import { createInertiaApp } from '@inertiajs/vue3' createInertiaApp({ resolve: name => { const pages = import.meta.glob('./Pages/**/*.vue', { eager: true }) return pages[`./Pages/${name}.vue`] }, setup({ el, App, props, plugin }) { createApp({ render: () => h(App, props) }) .use(plugin) .mount(el) }, }) ``` ```jsx import { createInertiaApp } from '@inertiajs/react' import { createRoot } from 'react-dom/client' createInertiaApp({ resolve: name => { const pages = import.meta.glob('./Pages/**/*.jsx', { eager: true }) return pages[`./Pages/${name}.jsx`] }, setup({ el, App, props }) { createRoot(el).render() }, }) ``` ```js import { createInertiaApp } from '@inertiajs/svelte' import { mount } from 'svelte' createInertiaApp({ resolve: name => { const pages = import.meta.glob('./Pages/**/*.svelte', { eager: true }) return pages[`./Pages/${name}.svelte`] }, setup({ el, App, props }) { mount(App, { target: el, props }) }, }) ``` -------------------------------- ### Install React Dependencies Source: https://inertiajs.com/docs/v2/installation/client-side-setup Install React, ReactDOM, and its Vite plugin using npm. These are required for React-based Inertia applications. ```bash npm install react react-dom @vitejs/plugin-react ``` -------------------------------- ### Start Inertia SSR Server with Bun Runtime Source: https://inertiajs.com/docs/v2/advanced/server-side-rendering Starts the Inertia SSR server using the Bun runtime instead of the default Node.js. Use the `--runtime` option to specify the desired runtime. ```bash php artisan inertia:start-ssr --runtime=bun ``` -------------------------------- ### Build SSR with Laravel Starter Kits Source: https://inertiajs.com/docs/v2/advanced/server-side-rendering Use this command to build for SSR when using Laravel starter kits. Ensure you have the necessary dependencies installed. ```bash npm run build:ssr ``` -------------------------------- ### Install Dynamic Import Plugin for Webpack Source: https://inertiajs.com/docs/v2/advanced/code-splitting Install the required Babel plugin to support dynamic imports in Webpack. ```bash npm install @babel/plugin-syntax-dynamic-import ``` -------------------------------- ### Setting HTTP Method for Manual Visits Source: https://inertiajs.com/docs/v2/the-basics/manual-visits Use the `method` option to specify the HTTP method for a manual visit. The default is 'get'. This example shows how to set it to 'post'. ```js import { router } from '@inertiajs/vue3' router.visit(url, { method: 'post' }) ``` ```js import { router } from '@inertiajs/react' router.visit(url, { method: 'post' }) ``` ```js import { router } from '@inertiajs/svelte' router.visit(url, { method: 'post' }) ``` -------------------------------- ### Start Progress Bar with Delay Source: https://inertiajs.com/docs/v2/advanced/progress-indicators Modify the 'start' event listener to initiate a timeout that shows the NProgress bar after a specified delay (e.g., 250ms). ```javascript router.on('start', () => { timeout = setTimeout(() => NProgress.start(), 250) }) ``` -------------------------------- ### Install Svelte Dependencies Source: https://inertiajs.com/docs/v2/installation/client-side-setup Install Svelte and its Vite plugin using npm. This is necessary for Svelte-based Inertia applications. ```bash npm install svelte @sveltejs/vite-plugin-svelte ``` -------------------------------- ### React Form with useForm Source: https://inertiajs.com/docs/v2/the-basics/forms Example of a login form using the useForm helper in React. It shows how to manage form data, handle input changes, and submit the form. ```jsx import { useForm } from '@inertiajs/react' const { data, setData, post, processing, errors } = useForm({ email: '', password: '', remember: false, }) function submit(e) { e.preventDefault() post('/login') } return (
setData('email', e.target.value)} /> {errors.email &&
{errors.email}
} setData('password', e.target.value)} /> {errors.password &&
{errors.password}
} setData('remember', e.target.checked)} /> Remember Me
) ``` -------------------------------- ### Start Inertia SSR Server Source: https://inertiajs.com/docs/v2/advanced/server-side-rendering Starts the Node-based Inertia SSR server. This command is essential for enabling server-side rendering in your Inertia.js application. ```bash php artisan inertia:start-ssr ``` -------------------------------- ### Page Object with Deferred Props Source: https://inertiajs.com/docs/v2/core-concepts/the-protocol Example showing the inclusion of deferredProps configuration for lazy-loaded data. ```json { "component": "Posts/Index", "props": { "errors": {}, "user": { "name": "Jonathan" } }, "url": "/posts", "version": "6b16b94d7c51cbe5b1fa42aac98241d5", "clearHistory": false, "encryptHistory": false, "deferredProps": { "default": [ "comments", "analytics" ], "sidebar": [ "relatedPosts" ] } } ``` -------------------------------- ### Svelte Form with useForm (v5) Source: https://inertiajs.com/docs/v2/the-basics/forms Example of a login form using the useForm helper in Svelte (v5). It shows how to bind input values and handle form submission. ```svelte
{#if $form.errors.email}
{$form.errors.email}
{/if} {#if $form.errors.password}
{$form.errors.password}
{/if} Remember Me
``` -------------------------------- ### Form Submission Methods Source: https://inertiajs.com/docs/v2/the-basics/forms Demonstrates the available submission methods (get, post, put, patch, delete) for the useForm helper across different frameworks. ```js form.submit(method, url, options) form.get(url, options) form.post(url, options) form.put(url, options) form.patch(url, options) form.delete(url, options) ``` ```js const { submit, get, post, put, patch, delete: destroy } = useForm({ ... }) submit(method, url, options) get(url, options) post(url, options) put(url, options) patch(url, options) destroy(url, options) ``` ```js $form.submit(method, url, options) $form.get(url, options) $form.post(url, options) $form.put(url, options) $form.patch(url, options) $form.delete(url, options) ``` -------------------------------- ### Combining Prefetch Strategies (React) Source: https://inertiajs.com/docs/v2/data-props/prefetching Combine multiple prefetch strategies by passing an array of strings to the `prefetch` prop in React. Example combines 'mount' and 'hover'. ```jsx import { Link } from '@inertiajs/react' Users ``` -------------------------------- ### Svelte Form with useForm (v3) Source: https://inertiajs.com/docs/v2/the-basics/forms Example of a login form using the useForm helper in Svelte (v3). It demonstrates binding input values and handling form submission. ```svelte
{#if $form.errors.email}
{$form.errors.email}
{/if} {#if $form.errors.password}
{$form.errors.password}
{/if} Remember Me
``` -------------------------------- ### Form Component with Events in React Source: https://inertiajs.com/docs/v2/the-basics/forms This example demonstrates how to use the Form component and handle its events in a React application. ```jsx
``` -------------------------------- ### Combining Prefetch Strategies (Vue) Source: https://inertiajs.com/docs/v2/data-props/prefetching Combine multiple prefetch strategies by passing an array of strings to the `prefetch` prop in Vue. Example combines 'mount' and 'hover'. ```vue import { Link } from '@inertiajs/vue3' Users ``` -------------------------------- ### Include NProgress Styles Source: https://inertiajs.com/docs/v2/advanced/progress-indicators Add the NProgress CSS styles to your project, for example, by using a CDN link. ```html ``` -------------------------------- ### Vue Form with useForm Source: https://inertiajs.com/docs/v2/the-basics/forms Example of a login form using the useForm helper in Vue. It demonstrates binding input values, displaying errors, and handling form submission. ```vue ``` -------------------------------- ### Render Inertia Page from Controller Source: https://inertiajs.com/docs/v2/the-basics/pages Example of rendering an Inertia page ('User/Show') from a Laravel controller, passing user data. ```php use Inertia\Inertia; class UserController extends Controller { public function show(User $user) { return Inertia::render('User/Show', [ 'user' => $user ]); } } ``` -------------------------------- ### Combining Prefetch Strategies (Svelte) Source: https://inertiajs.com/docs/v2/data-props/prefetching Combine multiple prefetch strategies by passing an array of strings to the `prefetch` property within the `inertia` directive in Svelte. Example combines 'mount' and 'hover'. ```svelte import { inertia } from '@inertiajs/svelte' Users ``` -------------------------------- ### React SSR Server Entry Point Configuration Source: https://inertiajs.com/docs/v2/advanced/server-side-rendering Configure the SSR entry point for React applications. This setup is for Node.js environments and includes necessary imports and rendering logic. ```jsx import { createInertiaApp } from '@inertiajs/react' import createServer from '@inertiajs/react/server' import ReactDOMServer from 'react-dom/server' createServer(page => createInertiaApp({ page, render: ReactDOMServer.renderToString, resolve: name => { const pages = import.meta.glob('./Pages/**/*.jsx', { eager: true }) return pages[`./Pages/${name}.jsx`] }, setup: ({ App, props }) => , }), ) ``` -------------------------------- ### Sending Data with HTTP Methods Source: https://inertiajs.com/docs/v2/the-basics/manual-visits For convenience, the `get()`, `post()`, `put()`, and `patch()` methods directly accept data as their second argument, simplifying requests. ```js import { router } from '@inertiajs/vue3' router.post('/users', { name: 'John Doe', email: 'john.doe@example.com', }) ``` ```js import { router } from '@inertiajs/react' router.post('/users', { name: 'John Doe', email: 'john.doe@example.com', }) ``` ```js import { router } from '@inertiajs/svelte' router.post('/users', { name: 'John Doe', email: 'john.doe@example.com', }) ``` -------------------------------- ### Handle Asset Versioning Conflict Source: https://inertiajs.com/docs/v2/core-concepts/the-protocol Example of a 409 Conflict response triggered when the client's asset version does not match the server's version. ```http REQUEST GET: https://example.com/events/80 Accept: text/html, application/xhtml+xml X-Requested-With: XMLHttpRequest X-Inertia: true X-Inertia-Version: 6b16b94d7c51cbe5b1fa42aac98241d5 RESPONSE 409: Conflict X-Inertia-Location: https://example.com/events/80 ``` -------------------------------- ### Svelte SSR Server Entry Point Configuration Source: https://inertiajs.com/docs/v2/advanced/server-side-rendering Configure the SSR entry point for Svelte applications. This setup is for Node.js environments and includes necessary imports and rendering logic. ```js import { createInertiaApp } from '@inertiajs/svelte' import createServer from '@inertiajs/svelte/server' import { render } from 'svelte/server' createServer(page => createInertiaApp({ page, resolve: name => { const pages = import.meta.glob('./Pages/**/*.svelte', { eager: true }) return pages[`./Pages/${name}.svelte`] }, setup({ App, props }) { return render(App, { props }) }, }), ) ``` -------------------------------- ### Page Object with Deferred Props Example Source: https://inertiajs.com/docs/v2/core-concepts/the-protocol Demonstrates an Inertia.js page object configured with deferred props, where certain props are loaded lazily in a subsequent request. ```APIDOC ### Page Object with Deferred Props When using deferred props, the page object includes a `deferredProps` configuration. Note that deferred props are not included in the initial props since they are loaded in a subsequent request. ```json { "component": "Posts/Index", "props": { "errors": {}, "user": { "name": "Jonathan" } }, "url": "/posts", "version": "6b16b94d7c51cbe5b1fa42aac98241d5", "clearHistory": false, "encryptHistory": false, "deferredProps": { "default": [ "comments", "analytics" ], "sidebar": [ "relatedPosts" ] } } ``` ``` -------------------------------- ### Enable Clustering for React SSR Source: https://inertiajs.com/docs/v2/advanced/server-side-rendering Enable clustering for the React SSR server by passing an options object with `cluster: true` to `createServer`. This starts multiple Node servers on the same port. ```jsx import { createInertiaApp } from '@inertiajs/react' import createServer from '@inertiajs/react/server' import ReactDOMServer from 'react-dom/server' createServer(page => createInertiaApp({ // ... }), { cluster: true }, ) ``` -------------------------------- ### Enable Clustering for Svelte SSR Source: https://inertiajs.com/docs/v2/advanced/server-side-rendering Enable clustering for the Svelte SSR server by passing an options object with `cluster: true` to `createServer`. This starts multiple Node servers on the same port. ```js import { createInertiaApp } from '@inertiajs/svelte' import createServer from '@inertiajs/svelte/server' import { render } from 'svelte/server' createServer(page => createInertiaApp({ // ... }), { cluster: true }, ) ``` -------------------------------- ### Vue SSR Server Entry Point Configuration Source: https://inertiajs.com/docs/v2/advanced/server-side-rendering Configure the SSR entry point for Vue.js applications. This setup is for Node.js environments and includes necessary imports and rendering logic. ```js import { createInertiaApp } from '@inertiajs/vue3' import createServer from '@inertiajs/vue3/server' import { renderToString } from 'vue/server-renderer' import { createSSRApp, h } from 'vue' createServer(page => createInertiaApp({ page, render: renderToString, resolve: name => { const pages = import.meta.glob('./Pages/**/*.vue', { eager: true }) return pages[`./Pages/${name}.vue`] }, setup({ App, props, plugin }) { return createSSRApp({ render: () => h(App, props), }).use(plugin) }, }), ) ``` -------------------------------- ### Initial HTML Response Example Source: https://inertiajs.com/docs/v2/core-concepts/the-protocol The first request to an Inertia app returns a full HTML document. This includes site assets and a root `
` with a `data-page` attribute containing JSON-encoded page data for initial client-side booting. ```http GET: https://example.com/events/80 Accept: text/html, application/xhtml+xml HTTP/1.1 200 OK Content-Type: text/html; charset=utf-8 My app
``` -------------------------------- ### Check if Progress Bar Started in Progress Event Source: https://inertiajs.com/docs/v2/advanced/progress-indicators Similarly, ensure the progress bar has started before updating its progress in the 'progress' event listener. ```javascript router.on('progress', event => { if (!NProgress.isStarted()) { return } // ... }) ``` -------------------------------- ### Configure prefetch with visit options Source: https://inertiajs.com/docs/v2/data-props/prefetching Pass visit options to usePrefetch to differentiate request configurations. ```js import { usePrefetch } from '@inertiajs/vue3' const { lastUpdatedAt, isPrefetching, isPrefetched, flush } = usePrefetch({ headers: { 'X-Custom-Header': 'value' } }) ``` ```js import { usePrefetch } from '@inertiajs/react' const { lastUpdatedAt, isPrefetching, isPrefetched, flush } = usePrefetch({ headers: { 'X-Custom-Header': 'value' } }) ``` ```js import { usePrefetch } from '@inertiajs/svelte' const { lastUpdatedAt, isPrefetching, isPrefetched, flush } = usePrefetch({ headers: { 'X-Custom-Header': 'value' } }) ``` -------------------------------- ### Build Client and Server Bundles Source: https://inertiajs.com/docs/v2/advanced/server-side-rendering Execute the updated NPM build script to generate both client-side and server-side rendering bundles for your application. ```bash npm run build ``` -------------------------------- ### Check if Progress Bar Started Before Finishing Source: https://inertiajs.com/docs/v2/advanced/progress-indicators Before calling `NProgress.done()`, check if the progress bar has actually started to avoid showing it prematurely after a delay. ```javascript router.on('finish', (event) => { clearTimeout(timeout) if (!NProgress.isStarted()) { return } // ... }) ``` -------------------------------- ### Configure Async Visit Options Source: https://inertiajs.com/docs/v2/advanced/progress-indicators Performs asynchronous requests with or without the default progress indicator. ```js // Disable the progress indicator router.get('/settings', {}, { async: true }) // Enable the progress indicator with async requests router.get('/settings', {}, { async: true, showProgress: true }) ``` -------------------------------- ### Preserve State with `get` Method Source: https://inertiajs.com/docs/v2/the-basics/manual-visits Use `preserveState: true` with the `get` method to maintain the component's state across visits. This is useful for preserving search parameters or scroll positions. ```Vue import { router } from '@inertiajs/vue3' router.get('/users', { search: 'John' }, { preserveState: true }) ``` ```React import { router } from '@inertiajs/react' router.get('/users', { search: 'John' }, { preserveState: true }) ``` ```Svelte import { router } from '@inertiajs/svelte' router.get('/users', { search: 'John' }, { preserveState: true }) ``` -------------------------------- ### Initialize Form with Method and URL (Precognition) Source: https://inertiajs.com/docs/v2/the-basics/forms For backwards compatibility with laravel-precognition packages, initialize the useForm helper with the HTTP method and URL as the first arguments. ```js const form = useForm('post', '/users', { name: '', email: '', }) ``` -------------------------------- ### Implement ProvidesInertiaProperty Source: https://inertiajs.com/docs/v2/the-basics/responses Create a class that implements ProvidesInertiaProperty to transform data into a specific format for Inertia props. ```php use Inertia\PropertyContext; use Inertia\ProvidesInertiaProperty; class UserAvatar implements ProvidesInertiaProperty { public function __construct(protected User $user, protected int $size = 64) { // } public function toInertiaProperty(PropertyContext $context): mixed { return $this->user->avatar ? Storage::url($this->user->avatar) : "https://ui-avatars.com/api/?name={$this->user->name}&size={$this->size}"; } } ``` -------------------------------- ### Enable View Transitions Globally (Svelte) Source: https://inertiajs.com/docs/v2/the-basics/view-transitions Configure the `visitOptions` callback in your Inertia app initialization to globally enable view transitions for all visits. ```javascript import { createInertiaApp } from '@inertiajs/svelte' createInertiaApp({ // ... defaults: { visitOptions: (href, options) => { return { viewTransition: true } }, }, }) ``` -------------------------------- ### Install Inertia Laravel dependency Source: https://inertiajs.com/docs/v2/installation/server-side-setup Use Composer to add the official Inertia server-side adapter to your Laravel project. ```bash composer require inertiajs/inertia-laravel ``` -------------------------------- ### Create SSR Entry Point for React Source: https://inertiajs.com/docs/v2/advanced/server-side-rendering Creates the SSR entry point file for React applications. This file will be used by Node.js for server-side rendering. ```bash touch resources/js/ssr.jsx ``` -------------------------------- ### Perform Partial Reload Request Source: https://inertiajs.com/docs/v2/core-concepts/the-protocol Example of a request and response for a partial reload, where only specific props are returned for the component. ```http REQUEST GET: https://example.com/events Accept: text/html, application/xhtml+xml X-Requested-With: XMLHttpRequest X-Inertia: true X-Inertia-Version: 6b16b94d7c51cbe5b1fa42aac98241d5 X-Inertia-Partial-Data: events X-Inertia-Partial-Component: Events RESPONSE HTTP/1.1 200 OK Content-Type: application/json { "component": "Events", "props": { "auth": {...}, // NOT included "categories": [...], // NOT included "events": [...], // Included "errors": {} // ALWAYS included }, "url": "/events/80", "version": "6b16b94d7c51cbe5b1fa42aac98241d5" } ``` -------------------------------- ### Vue Layout Component Source: https://inertiajs.com/docs/v2/the-basics/pages A typical Vue layout component using Inertia.js links for navigation. Ensure you have '@inertiajs/vue3' installed. ```vue ``` -------------------------------- ### Import NProgress and Inertia Router (Svelte) Source: https://inertiajs.com/docs/v2/advanced/progress-indicators Import NProgress and the Inertia router for Svelte applications. ```javascript import NProgress from 'nprogress' import { router } from '@inertiajs/svelte' ``` -------------------------------- ### Configure Global Visit Options Source: https://inertiajs.com/docs/v2/the-basics/manual-visits Use the `visitOptions` callback within the `defaults` object during Inertia app initialization to globally modify visit options. This callback receives the target URL and current options, and should return an object with any options to override, such as adding custom headers. ```js import { createApp, h } from 'vue' import { createInertiaApp } from '@inertiajs/vue3' createInertiaApp({ // ... defaults: { visitOptions: (href, options) => { return { headers: { ...options.headers, 'X-Custom-Header': 'value', }, } }, }, }) ``` ```jsx import { createInertiaApp } from '@inertiajs/react' import { createRoot } from 'react-dom/client' createInertiaApp({ // ... defaults: { visitOptions: (href, options) => { return { headers: { ...options.headers, 'X-Custom-Header': 'value', }, } }, }, }) ``` ```js import { createInertiaApp } from '@inertiajs/svelte' createInertiaApp({ // ... defaults: { visitOptions: (href, options) => { return { headers: { ...options.headers, 'X-Custom-Header': 'value', }, } }, }, }) ``` -------------------------------- ### React Page Component Source: https://inertiajs.com/docs/v2/the-basics/pages Example of an Inertia page component written in React. It utilizes a layout and receives user data as a prop. ```jsx import Layout from './Layout' import { Head } from '@inertiajs/react' export default function Welcome({ user }) { return (

Welcome

Hello {user.name}, welcome to your first Inertia app!

) } ``` -------------------------------- ### Vue Page Component Source: https://inertiajs.com/docs/v2/the-basics/pages Example of an Inertia page component written in Vue. It uses a layout and receives user data as a prop. ```vue ``` -------------------------------- ### Basic Page Object Example Source: https://inertiajs.com/docs/v2/core-concepts/the-protocol A minimal Inertia.js page object includes the essential properties for rendering a component and managing navigation. ```APIDOC ### Basic Page Object A minimal page object contains the core properties. ```json { "component": "User/Edit", "props": { "errors": {}, "user": { "name": "Jonathan" } }, "url": "/user/123", "version": "6b16b94d7c51cbe5b1fa42aac98241d5", "clearHistory": false, "encryptHistory": false } ``` ``` -------------------------------- ### Define Inertia Macro for Fractal Scroll Source: https://inertiajs.com/docs/v2/data-props/infinite-scroll Create a reusable Inertia macro in AppServiceProvider to simplify the setup for Fractal-based infinite scrolling. ```php // In your AppServiceProvider's boot method Inertia::macro('fractalScroll', function (Collection $data) { return Inertia::scroll( $data, metadata: fn(Collection $data) => new FractalScrollMetadata($data) ); }); // Then use it in your controllers return Inertia::render('Users/Index', [ 'users' => Inertia::fractalScroll($fractalCollection) ]); ``` -------------------------------- ### JSON Data Structure for Nested Forms Source: https://inertiajs.com/docs/v2/the-basics/forms This JSON represents the data structure generated from the previous form example with dotted key notation. ```json { "user": { "name": "John Doe", "skills": ["JavaScript"] }, "address": { "street": "123 Main St" } } ``` -------------------------------- ### Form Component with Events Source: https://inertiajs.com/docs/v2/the-basics/forms The Form component emits standard visit events for form submissions. This example shows how to listen to these events in Vue. ```vue ``` -------------------------------- ### Configure Vite for Code Splitting Source: https://inertiajs.com/docs/v2/advanced/code-splitting Enable lazy-loading by removing the eager: true option from import.meta.glob. ```js resolve: name => { const pages = import.meta.glob('./Pages/**/*.vue', { eager: true }) // [!code --:2] return pages[`./Pages/${name}.vue`] const pages = import.meta.glob('./Pages/**/*.vue') // [!code ++:2] return pages[`./Pages/${name}.vue`]() }, ``` ```js resolve: name => { const pages = import.meta.glob('./Pages/**/*.jsx', { eager: true }) // [!code --:2] return pages[`./Pages/${name}.jsx`] const pages = import.meta.glob('./Pages/**/*.jsx') // [!code ++:2] return pages[`./Pages/${name}.jsx`]() }, ``` ```js resolve: name => { const pages = import.meta.glob('./Pages/**/*.svelte', { eager: true }) // [!code --:2] return pages[`./Pages/${name}.svelte`] const pages = import.meta.glob('./Pages/**/*.svelte') // [!code ++:2] return pages[`./Pages/${name}.svelte`]() }, ``` -------------------------------- ### Enable View Transitions Globally (React) Source: https://inertiajs.com/docs/v2/the-basics/view-transitions Configure the `visitOptions` callback in your Inertia app initialization to globally enable view transitions for all visits. ```javascript import { createInertiaApp } from '@inertiajs/react' createInertiaApp({ // ... defaults: { visitOptions: (href, options) => { return { viewTransition: true } }, }, }) ``` -------------------------------- ### Form Component with Events in Svelte (v3/v4) Source: https://inertiajs.com/docs/v2/the-basics/forms This example shows how to integrate the Form component and manage form submission events within a Svelte application. ```svelte
``` -------------------------------- ### Import NProgress and Inertia Router (Vue) Source: https://inertiajs.com/docs/v2/advanced/progress-indicators Import NProgress and the Inertia router for Vue applications. ```javascript import NProgress from 'nprogress' import { router } from '@inertiajs/vue3' ``` -------------------------------- ### Enable View Transitions Globally (Vue) Source: https://inertiajs.com/docs/v2/the-basics/view-transitions Configure the `visitOptions` callback in your Inertia app initialization to globally enable view transitions for all visits. ```javascript import { createInertiaApp } from '@inertiajs/vue3' createInertiaApp({ // ... defaults: { visitOptions: (href, options) => { return { viewTransition: true } }, }, }) ``` -------------------------------- ### Svelte 5 Page Component Source: https://inertiajs.com/docs/v2/the-basics/pages Example of an Inertia page component written in Svelte 5. It uses a layout and receives user data as a prop. ```svelte Welcome

Welcome

Hello {user.name}, welcome to your first Inertia app!

``` -------------------------------- ### Svelte 4 Page Component Source: https://inertiajs.com/docs/v2/the-basics/pages Example of an Inertia page component written in Svelte 4. It includes a layout and passes user data as a prop. ```svelte Welcome

Welcome

Hello {user.name}, welcome to your first Inertia app!

``` -------------------------------- ### Use Custom Metadata Provider with Inertia::scroll() Source: https://inertiajs.com/docs/v2/data-props/infinite-scroll Apply a custom metadata provider, such as FractalScrollMetadata, directly or via a callback to Inertia::scroll(). ```php // Using an instance directly Inertia::scroll($data, metadata: new FractalScrollMetadata($data)); // Using a callback Inertia::scroll( fn() => $this->transformData($data), metadata: fn($data) => new FractalScrollMetadata($data) ); ``` -------------------------------- ### Configure pnpm to hoist @inertiajs/core Source: https://inertiajs.com/docs/v2/advanced/typescript When using pnpm, hoist @inertiajs/core to resolve module augmentation issues. Add this to your .npmrc file and run pnpm install. ```ini public-hoist-pattern[]=@inertiajs/core ``` -------------------------------- ### Render with property groups Source: https://inertiajs.com/docs/v2/the-basics/responses Use classes implementing ProvidesInertiaProperties directly in render or with methods. ```php public function index(UserPermissions $permissions) { return Inertia::render('UserProfile', $permissions); // or... return Inertia::render('UserProfile')->with($permissions); } ``` ```php public function index(UserPermissions $permissions) { return Inertia::render('UserProfile', [ 'user' => auth()->user(), $permissions, ]); // or using method chaining... return Inertia::render('UserProfile') ->with('user', auth()->user()) ->with($permissions); } ``` -------------------------------- ### Form Submission with Callbacks (React) Source: https://inertiajs.com/docs/v2/the-basics/forms Example of submitting a form with options like `preserveScroll` and an `onSuccess` callback to reset specific fields after a successful submission in React. ```js const { post, reset } = useForm({ ... }) post('/profile', { preserveScroll: true, onSuccess: () => reset('password'), }) ``` -------------------------------- ### Import NProgress and Inertia Router (React) Source: https://inertiajs.com/docs/v2/advanced/progress-indicators Import NProgress and the Inertia router for React applications. ```javascript import NProgress from 'nprogress' import { router } from '@inertiajs/react' ``` -------------------------------- ### Form Submission with Callbacks (Vue) Source: https://inertiajs.com/docs/v2/the-basics/forms Example of submitting a form with options like `preserveScroll` and an `onSuccess` callback to reset specific fields after a successful submission in Vue. ```js form.post('/profile', { preserveScroll: true, onSuccess: () => form.reset('password'), }) ``` -------------------------------- ### JSON Data Structure with Escaped Dots Source: https://inertiajs.com/docs/v2/the-basics/forms This JSON represents the data structure generated from the form example using escaped dots for literal field names. ```json { "app.name": "My Application", "settings": { "theme.mode": "dark" } } ``` -------------------------------- ### Implement Custom Loading Indicator with NProgress Source: https://inertiajs.com/docs/v2/advanced/progress-indicators Uses Inertia router events to trigger and manage NProgress loading states. Requires the nprogress package and the corresponding Inertia adapter. ```Vue import NProgress from 'nprogress' import { router } from '@inertiajs/vue3' let timeout = null router.on('start', () => { timeout = setTimeout(() => NProgress.start(), 250) }) router.on('progress', (event) => { if (NProgress.isStarted() && event.detail.progress.percentage) { NProgress.set((event.detail.progress.percentage / 100) * 0.9) } }) router.on('finish', (event) => { clearTimeout(timeout) if (!NProgress.isStarted()) { return } if (event.detail.visit.completed) { NProgress.done() } else if (event.detail.visit.interrupted) { NProgress.set(0) } else if (event.detail.visit.cancelled) { NProgress.done() NProgress.remove() } }) ``` ```React import NProgress from 'nprogress' import { router } from '@inertiajs/react' let timeout = null router.on('start', () => { timeout = setTimeout(() => NProgress.start(), 250) }) router.on('progress', (event) => { if (NProgress.isStarted() && event.detail.progress.percentage) { NProgress.set((event.detail.progress.percentage / 100) * 0.9) } }) router.on('finish', (event) => { clearTimeout(timeout) if (!NProgress.isStarted()) { return } if (event.detail.visit.completed) { NProgress.done() } else if (event.detail.visit.interrupted) { NProgress.set(0) } else if (event.detail.visit.cancelled) { NProgress.done() NProgress.remove() } }) ``` ```Svelte import NProgress from 'nprogress' import { router } from '@inertiajs/svelte' let timeout = null router.on('start', () => { timeout = setTimeout(() => NProgress.start(), 250) }) router.on('progress', (event) => { if (NProgress.isStarted() && event.detail.progress.percentage) { NProgress.set((event.detail.progress.percentage / 100) * 0.9) } }) router.on('finish', (event) => { clearTimeout(timeout) if (!NProgress.isStarted()) { return } if (event.detail.visit.completed) { NProgress.done() } else if (event.detail.visit.interrupted) { NProgress.set(0) } else if (event.detail.visit.cancelled) { NProgress.done() NProgress.remove() } }) ``` -------------------------------- ### React: Multiple Head Instances Source: https://inertiajs.com/docs/v2/the-basics/title-and-meta Use multiple `` components in React layouts and pages. Use `head-key` to ensure unique meta tags like descriptions. ```jsx // Layout.js import { Head } from '@inertiajs/react' My app // About.js import { Head } from '@inertiajs/react' About - My app ``` -------------------------------- ### Create SSR Entry Point for Vue Source: https://inertiajs.com/docs/v2/advanced/server-side-rendering Creates the SSR entry point file for Vue.js applications. This file will be used by Node.js for server-side rendering. ```bash touch resources/js/ssr.js ``` -------------------------------- ### Manual Poll Control Source: https://inertiajs.com/docs/v2/data-props/polling Prevent automatic polling on mount by setting `autoStart: false`. Use the returned `start` and `stop` methods to manually control the polling behavior. ```vue ``` ```react import { usePoll } from '@inertiajs/react' export default () => { const { start, stop } = usePoll(2000, {}, { autoStart: false, }) return (
) } ``` ```svelte import { usePoll } from '@inertiajs/svelte' const { start, stop } = usePoll(2000, {}, { autoStart: false, }) ``` -------------------------------- ### Handle Standard Redirects in Controller Source: https://inertiajs.com/docs/v2/the-basics/redirects When creating or updating resources, return a redirect to a GET endpoint like the index page. Inertia automatically follows and updates the page. ```php class UsersController extends Controller { public function index() { return Inertia::render('Users/Index', [ 'users' => User::all(), ]); } public function store(Request $request) { User::create( $request->validate([ 'name' => ['required', 'max:50'], 'email' => ['required', 'max:50', 'email'], ]) ); return to_route('users.index'); } } ``` -------------------------------- ### Store User and Redirect Source: https://inertiajs.com/docs/v2/the-basics/forms This controller method demonstrates creating a new user based on validated request data and then returning a redirect response to the users index page. ```php class UsersController extends Controller { public function index() { return Inertia::render('Users/Index', [ 'users' => User::all(), ]); } public function store(Request $request) { User::create($request->validate([ 'first_name' => ['required', 'max:50'], 'last_name' => ['required', 'max:50'], 'email' => ['required', 'max:50', 'email'], ])); return to_route('users.index'); } } ``` -------------------------------- ### Basic HTML Form with Inertia Source: https://inertiajs.com/docs/v2/the-basics/forms Use the Form component like a standard HTML form. Provide 'action' and 'method' props. Input fields only require a 'name' attribute. ```svelte
``` -------------------------------- ### Implement File Uploads with Form Helper Source: https://inertiajs.com/docs/v2/the-basics/file-uploads Use the useForm helper to manage form state and track upload progress for file inputs. ```vue ``` ```jsx import { useForm } from '@inertiajs/react' const { data, setData, post, progress } = useForm({ name: null, avatar: null, }) function submit(e) { e.preventDefault() post('/users') } return (
setData('name', e.target.value)} /> setData('avatar', e.target.files[0])} /> {progress && ( {progress.percentage}% )}
) ``` ```svelte
$form.avatar = e.target.files[0]} /> {#if $form.progress} {$form.progress.percentage}% {/if}
``` ```svelte
$form.avatar = e.target.files[0]} /> {#if $form.progress} {$form.progress.percentage}% {/if}
```