### Getting Started: Basic Mocha Test Setup
Source: https://mochajs.org/
Demonstrates how to set up a basic test file using Mocha and the built-in Node.js 'assert' module. Includes steps for installation, creating a test file, writing a simple test case, and running it via the command line.
```bash
npm install mocha
mkdir test
$EDITOR test/test.js
```
```javascript
var assert = require("assert");
describe("Array", function () {
describe("#indexOf()", function () {
it("should return -1 when the value is not present", function () {
assert.equal([1, 2, 3].indexOf(4), -1);
});
});
});
```
```bash
./node_modules/mocha/bin/mocha.js Array #indexOf()
# Expected output:
# Array #indexOf()
# ✓ should return -1 when the value is not present
#
# 1 passing (9ms)
```
--------------------------------
### Install and Build Laravel App
Source: https://laravel.com/docs/starter-kits
Commands to create a new Laravel application using the installer, install frontend dependencies via NPM, and start the development server. Assumes the Laravel installer is available.
```bash
laravel new my-app
cd my-app
npm install && npm run build
composer run dev
```
--------------------------------
### Install and Create a New Laravel App
Source: https://laravel.com/
This snippet demonstrates how to install the Laravel installer globally using Composer and then create a new Laravel application. It's a common starting point for new Laravel projects.
```bash
composer global require laravel/installer
laravel new example-app
```
--------------------------------
### Install Inertia Client-side Adapter (Vue)
Source: https://inertiajs.com/client-side-setup
Installs the Inertia.js client-side adapter specifically for Vue 3 using npm. This is a prerequisite for initializing the Inertia app with Vue.
```bash
npm install @inertiajs/vue3
```
--------------------------------
### Podcasts Controller Test Example
Source: https://context7_llms
An example test case demonstrating how to test an Inertia response for a 'Podcasts/Show' component, asserting various properties and nested structures.
```APIDOC
## GET /podcasts/{id}
### Description
Tests the Inertia response for a specific podcast, verifying component name, nested data, and property existence.
### Method
GET
### Endpoint
/podcasts/{id}
### Parameters
#### Path Parameters
- **id** (integer) - Required - The ID of the podcast to retrieve.
### Request Example
```php
// No request body for GET requests
```
### Response
#### Success Response (200)
- **podcast** (object) - Details of the podcast, including its ID, subject, description, seasons, episodes, and host.
- **seasons** (integer) - The number of seasons for the podcast.
- **host** (object) - Information about the podcast host.
#### Response Example
```php
// Example response structure is implicitly tested by the AssertableInertia assertions
// A direct JSON response example is not provided as Inertia focuses on component rendering.
```
```php
use Inertia\Testing\AssertableInertia as Assert;
// Assuming $podcast is already defined and fetched
$this->get('/podcasts/41')
->assertInertia(fn (Assert $page) => $page
->component('Podcasts/Show')
->has('podcast', fn (Assert $page) => $page
->where('id', $podcast->id)
->where('subject', 'The Laravel Podcast')
->where('description', 'The Laravel Podcast brings you Laravel and PHP development news and discussion.')
->has('seasons', 4)
->has('seasons.4.episodes', 21)
->has('host', fn (Assert $page) => $page
->where('id', 1)
->where('name', 'Matt Stauffer')
)
->has('subscribers', 7, fn (Assert $page) => $page
->where('id', 2)
->where('name', 'Claudio Dekker')
->where('platform', 'Apple Podcasts')
->etc()
->missing('email')
->missing('password')
)
)
);
```
```
--------------------------------
### Setup Environment Configuration
Source: https://github.com/inertiajs/pingcrm
Copies the example environment file to a new file, which will store application-specific configurations.
```bash
cp .env.example .env
```
--------------------------------
### Mocha Root Hook Example (Serial Mode)
Source: https://mochajs.org/
An example demonstrating how to define and use root hooks (beforeEach, afterEach) in Mocha's serial mode. These hooks are executed globally for all test files. This example uses the 'bdd' interface and illustrates how a setup file can influence all subsequent tests.
```javascript
// test/setup.js
// root hook to run before every test (even in other files)
beforeEach(function () {
doMySetup();
});
// root hook to run after every test (even in other files)
afterEach(function () {
doMyTeardown();
});
```
--------------------------------
### Setup Environment and Generate Key
Source: https://github.com/inertiajs/pingcrm-svelte
Copies the example environment file and generates a new application key for Laravel. This is crucial for security and configuration.
```bash
cp .env.example .env
php artisan key:generate
```
--------------------------------
### Install Inertia Laravel Server-Side Adapter
Source: https://inertiajs.com/server-side-setup
This command installs the official Inertia.js server-side adapter for Laravel using Composer. It's the first step in integrating Inertia into a Laravel application.
```bash
composer require inertiajs/inertia-laravel
```
--------------------------------
### Ruby on Rails Application Setup Script
Source: https://github.com/ledermann/pingcrm
The `bin/setup` script is a common convention in Ruby on Rails projects. It automates the process of setting up the application, including installing dependencies, creating and seeding the database.
```bash
#!/usr/bin/env bash
set -e
# Install dependencies
if [ -f "Gemfile" ]; then
bundle install --jobs $(getconf _NPROCESSORS_ONLN)
else
echo "Gemfile not found. Skipping bundle install."
fi
# Create and seed database
if [ -f "config/database.yml" ]; then
rails db:create 2>/dev/null || true
rails db:migrate
rails db:seed
else
echo "config/database.yml not found. Skipping database setup."
fi
echo "Setup complete!"
```
--------------------------------
### Start Inertia SSR Server
Source: https://context7_llms
Starts the Node.js-based Inertia SSR server using the Artisan command. This command should be run after the client and server bundles have been built.
```bash
php artisan inertia:start-ssr
```
--------------------------------
### Mocha TDD Interface Example
Source: https://mochajs.org/
Demonstrates the Test-Driven Development (TDD) interface in MochaJS, using `suite`, `test`, `setup`, and `suiteTeardown` for organizing tests. This example tests array methods.
```javascript
suite("Array", function () {
setup(function () {
// ... setup
});
suite("#indexOf()", function () {
test("should return -1 when not present", function () {
assert.equal(-1, [1, 2, 3].indexOf(4));
});
});
});
```
--------------------------------
### Mocha Global Setup and Teardown Fixtures
Source: https://mochajs.org/
Demonstrates how to use global fixtures in MochaJS for starting and stopping a test server before and after all tests run. This is useful for setting up a consistent testing environment.
```javascript
// fixtures.mjs
let server;
export const mochaGlobalSetup = async () => {
server = await startSomeServer({ port: process.env.TEST_PORT });
console.log(`server running on port ${server.port}`);
};
export const mochaGlobalTeardown = async () => {
await server.stop();
console.log("server stopped!");
};
```
--------------------------------
### Basic Usage of defineOptions in Vue
```
--------------------------------
### Install Inertia Client-Side Adapters
Source: https://context7_llms
Installs the client-side Inertia adapter for various JavaScript frameworks using npm. Choose the adapter corresponding to your frontend framework (Vue, React, or Svelte).
```bash
npm install @inertiajs/vue3
```
```bash
npm install @inertiajs/react
```
```bash
npm install @inertiajs/svelte
```
--------------------------------
### React File Upload Example with Inertia Form Helper
Source: https://context7_llms
A React example demonstrating a file upload using Inertia's form helper. It includes a text input for a name and a file input for an avatar, showing how to submit the form and display upload progress.
```jsx
import { useForm } from '@inertiajs/react'
const { data, setData, post, progress } = useForm({
name: null,
avatar: null,
})
function submit(e) {
e.preventDefault()
post('/users')
}
return (
)
```
--------------------------------
### Start Inertia SSR Server with Bun Runtime
Source: https://context7_llms
Starts the Inertia SSR server using the Bun runtime instead of the default Node.js runtime. This is achieved by passing the `--runtime=bun` option to the Artisan command.
```bash
php artisan inertia:start-ssr --runtime=bun
```
--------------------------------
### Resolve Components with Vite (Vue)
Source: https://inertiajs.com/client-side-setup
Provides an example of the `resolve` callback used by Inertia to load page components, specifically configured for use with Vite. It utilizes `import.meta.glob` to dynamically import Vue components from a './Pages' directory.
```javascript
// Vite
resolve: name => {
const pages = import.meta.glob('./Pages/**/*.vue', { eager: true })
return pages[`./Pages/${name}.vue`]
}
```
--------------------------------
### Install Inertia.js Client-Side Adapters (npm)
Source: https://context7_llms
Installs the client-side adapters for Inertia.js v2.0 for Vue, React, and Svelte using npm. Ensure you are using compatible versions of your respective frameworks.
```bash
npm install @inertiajs/vue3@^2.0
```
```bash
npm install @inertiajs/react@^2.0
```
```bash
npm install @inertiajs/svelte@^2.0
```
--------------------------------
### Svelte 5 File Upload Example with Inertia Form Helper
Source: https://context7_llms
A Svelte 5 example demonstrating a file upload using Inertia's form helper. It includes a text input for a name and a file input for an avatar, showing how to submit the form and display upload progress.
```jsx
```
--------------------------------
### Advanced Generic Type Declarations in Vue
Source: https://vuejs.org/api/sfc-script-setup.html
Provides examples of more complex generic type declarations in Vue's `
```
--------------------------------
### Vue File Upload Example with Inertia Form Helper
Source: https://context7_llms
A Vue.js example demonstrating a file upload using Inertia's form helper. It includes a text input for a name and a file input for an avatar, showing how to submit the form and display upload progress.
```vue
```
--------------------------------
### Use Poll Helper with Options (Svelte)
Source: https://context7_llms
Demonstrates using the `usePoll` helper in Inertia.js for Svelte with additional request options. This example shows how to define `onStart` and `onFinish` callbacks to log when polling requests begin and end.
```javascript
import { usePoll } from '@inertiajs/svelte'
usePoll(2000, {
onStart() {
console.log('Polling request started')
},
onFinish() {
console.log('Polling request finished')
}
})
```
--------------------------------
### Vue JS: Equivalent of Reactive Props Destructuring
Source: https://vuejs.org/api/sfc-script-setup.html
Provides the JavaScript equivalent of the reactive props destructuring example, showing how the Vue compiler transforms destructured variables to reference 'props.variable' for reactivity.
```javascript
const props = defineProps(['foo'])
watchEffect(() => {
// `foo` transformed to `props.foo` by the compiler
console.log(props.foo)
})
```
--------------------------------
### Initial HTML Response Example
Source: https://context7_llms
The first request to an Inertia app receives a standard HTML document. This includes site assets and a root `
` with a `data-page` attribute containing the initial page object as JSON.
```html
My app
```
--------------------------------
### Use Poll Helper with Options (React)
Source: https://context7_llms
Demonstrates using the `usePoll` helper in Inertia.js for React with additional request options. This example shows how to define `onStart` and `onFinish` callbacks to log when polling requests begin and end.
```javascript
import { usePoll } from '@inertiajs/react'
usePoll(2000, {
onStart() {
console.log('Polling request started')
},
onFinish() {
console.log('Polling request finished')
}
})
```
--------------------------------
### Form Component Events (Vue, React, Svelte)
Source: https://context7_llms
Shows how to handle standard Inertia.js visit events emitted by the Form component, such as before, start, progress, success, error, finish, cancel, and cancelToken. Examples are provided for Vue, React, and Svelte.
```vue
```
```react
```
```svelte
```
--------------------------------
### Initialize Inertia App with React
Source: https://context7_llms
Initializes the Inertia.js client-side framework using React. It resolves page components from the './Pages/**/*.jsx' directory. This setup requires '@inertiajs/react' and 'react-dom/client'.
```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()
},
})
```
--------------------------------
### Install Laravel with a Starter Kit (Bash)
Source: https://laravel.com/docs/starter-kits
This command installs a new Laravel application using a specified community-maintained starter kit from Packagist. It requires the `laravel` installer to be globally available.
```bash
laravel new my-app --using=example/starter-kit
```
--------------------------------
### Browser Mocha Configuration Examples
Source: https://mochajs.org/
Illustrates various ways to configure Mocha in the browser using `mocha.setup()`. This includes setting the UI interface and other options like `allowUncaught`, `asyncOnly`, `bail`, etc.
```javascript
// Use "tdd" interface. This is a shortcut to setting the interface;
// any other options must be passed via an object.
mocha.setup('tdd');
// This is equivalent to the above.
mocha.setup({ ui: 'tdd' });
// Examples of options:
mocha.setup({
allowUncaught: true,
asyncOnly: true,
bail: true,
checkLeaks: true,
dryRun: true,
failZero: true,
forbidOnly: true,
forbidPending: true,
global: ['MyLib'],
retries: 3,
rootHooks: {
beforeEach(done) {
// ...
done();
}
},
slow: '100',
timeout: '2000',
ui: 'bdd'
});
```
--------------------------------
### Install Laravel Installer CLI
Source: https://laravel.com/docs/starter-kits
This snippet shows how to install the Laravel installer command-line interface tool globally using Composer. This tool is a prerequisite for creating new Laravel applications, including those using starter kits.
```bash
composer global require laravel/installer
```
--------------------------------
### Publish shadcn/ui Component
Source: https://laravel.com/docs/starter-kits
Example command to publish a shadcn/ui component, such as the 'switch' component, into the React application's resources. This command is executed using npx.
```bash
npx shadcn@latest add switch
```
--------------------------------
### Vue: Project Structure Overview
Source: https://laravel.com/docs/starter-kits
Overview of the directory structure for the Vue starter kit, located in `resources/js`. Key directories include `components`, `composables`, `layouts`, `lib`, `pages`, and `types` for organized development.
```text
resources/js/
├── components/ # Reusable Vue components
├── composables/ # Vue composables / hooks
├── layouts/ # Application layouts
├── lib/ # Utility functions and configuration
├── pages/ # Page components
└── types/ # TypeScript definitions
```
--------------------------------
### Setting HTTP Method with router.visit()
Source: https://context7_llms
Illustrates how to specify the HTTP method for an Inertia visit using the `method` option within the `router.visit()` call. Examples are provided for Vue, React, and Svelte, showing how to set the method to 'post'. This is useful for actions that require a specific HTTP verb beyond the default 'get'. Dependencies include the respective Inertia adapters.
```javascript
import { router } from '@inertiajs/vue3'
router.visit(url, { method: 'post' })
```
```javascript
import { router } from '@inertiajs/react'
router.visit(url, { method: 'post' })
```
```javascript
import { router } from '@inertiajs/svelte'
router.visit(url, { method: 'post' })
```
--------------------------------
### Heroku Procfile for Inertia.js SSR
Source: https://inertiajs.com/server-side-rendering
This configuration snippet for a Heroku `Procfile` shows how to start the Inertia.js SSR server before launching the main web server. It requires both `heroku/nodejs` and `heroku/php` buildpacks to be installed.
```bash
web: php artisan inertia:start-ssr & vendor/bin/heroku-php-apache2 public/
```
--------------------------------
### Install Babel Plugin for Webpack Dynamic Imports
Source: https://context7_llms
Installs the `@babel/plugin-syntax-dynamic-import` npm package, which is required to enable dynamic imports when using Webpack for code splitting in Inertia.js.
```bash
npm install @babel/plugin-syntax-dynamic-import
```
--------------------------------
### Vue.js: Basic
```
--------------------------------
### Database Setup and Migrations
Source: https://github.com/inertiajs/pingcrm-svelte
Creates an SQLite database file and runs database migrations to set up the schema. Supports other databases by updating the .env file.
```bash
touch database/database.sqlite
php artisan migrate
```
--------------------------------
### Inertia.js Server-Side Rendering Build Command
Source: https://laravel.com/docs/starter-kits
Demonstrates the npm command used to build an Inertia.js SSR compatible bundle for React and Vue starter kits. This command prepares the application for server-side rendering.
```bash
npm run build:ssr
npm run build:ssr
```
--------------------------------
### Specify HTTP Request Method for Inertia Links
Source: https://context7_llms
Control the HTTP request method (GET, POST, PUT, PATCH, DELETE) for Inertia links using the `method` prop. Defaults to GET.
```jsx
import { Link } from '@inertiajs/vue3'
Logout
```
```jsx
import { Link } from '@inertiajs/react'
Logout
```
```jsx
import { inertia, Link } from '@inertiajs/svelte'
Logout
```
--------------------------------
### Server Configuration Example
Source: https://github.com/tbreuss/pingcrm-mithril
A basic server.php file, typically used in Laravel for handling incoming requests and bootstrapping the application. This is the entry point for the web server.
```php
instance(Kernel::class, $app->make(Kernel::class));
});
/*
|--------------------------------------------------------------------------
| Run The Application
|
| Once we have the application, we can simply call the run
| method, which will execute the request and return the
| response. RuntimE is automatically handled.
|
*/
return tap($app->make(Kernel::class))->handle(
tap(request())->withParsedQueryString()
)->toResponse($app);
```
--------------------------------
### Axios GET Request with Query Parameters
Source: https://github.com/axios/axios
This example shows how to send a GET request with Axios, including query parameters. Axios automatically serializes the `params` object into a query string.
```javascript
axios.get('/users', {
params: {
ID: 12345,
status: 'active'
}
})
.then(function (response) {
console.log(response.data);
})
.catch(function (error) {
console.log(error);
});
```
--------------------------------
### Clone and Build PingCRM Echo from Source (Makefile)
Source: https://github.com/kohkimakimoto/pingcrm-echo
Instructions for cloning the PingCRM Echo repository and building the application from source using `make`. This involves cloning the git repository, installing dependencies with `make deps`, and building the development binary with `make build/dev`. The resulting binary will be located at `dev/build/outputs/dev/pingcrm-echo`.
```bash
git clone https://github.com/kohkimakimoto/pingcrm-echo.git
cd pingcrm-echo
make deps
make build/dev
```
--------------------------------
### Run Application in Development (REPL)
Source: https://github.com/prestancedesign/pingcrm-clojure
Starts the front-end with hot reloading and launches the back-end in a REPL environment for development. This allows for live code changes and interactive development.
```bash
npm run dev
clj -M:dev
(go)
```
--------------------------------
### NProgress Integration: Start and Finish Events
Source: https://context7_llms
Use Inertia's router events to control the NProgress indicator. The 'start' event initiates NProgress, and the 'finish' event completes it, providing visual feedback during navigation.
```javascript
router.on('start', () => NProgress.start())
router.on('finish', () => NProgress.done())
```
--------------------------------
### Livewire Blade Layouts
Source: https://laravel.com/docs/starter-kits
Defines the structure for reusable Livewire Blade components and partials within the resources/views directory. It shows how to include slots for dynamic content insertion in different layout variants.
```blade
{{ $slot }}
```
--------------------------------
### Basic Axios GET Request
Source: https://github.com/axios/axios
This example demonstrates a simple GET request using Axios to fetch data from a specified URL. It uses a promise-based approach to handle the response and potential errors.
```javascript
axios.get('/user?ID=12345')
.then(function (response) {
// handle success
console.log(response.data);
})
.catch(function (error) {
// handle error
console.log(error);
})
.finally(function () {
// always executed
});
```
--------------------------------
### Title Callback Example with Component (React)
Source: https://context7_llms
Demonstrates the integration of the global title callback with the Inertia `` component in React. When a title is set within the `` component, the callback is invoked to process it, as shown in this example.
```jsx
import { Head } from '@inertiajs/react'
```
--------------------------------
### Database Setup and Migrations
Source: https://github.com/Landish/pingcrm-react
Instructions to create an SQLite database, generate the application key, run database migrations, and seed the database.
```shell
php artisan key:generate
touch database/database.sqlite
php artisan migrate
php artisan db:seed
```
--------------------------------
### Install Axios using Package Managers
Source: https://github.com/axios/axios
Installs the Axios library using common package managers like npm, yarn, pnpm, and bun. This is the first step before importing and using Axios in your project.
```bash
npm install axios
```
```bash
bower install axios
```
```bash
yarn add axios
```
```bash
pnpm add axios
```
```bash
bun add axios
```
--------------------------------
### Inertia Delete Visit Example (Vue, React, Svelte)
Source: https://context7_llms
Provides basic examples for initiating a delete visit using Inertia.js across Vue, React, and Svelte. These snippets show the syntax for calling the `router.delete()` method with a user ID.
```vue
import { router } from '@inertiajs/vue3'
router.delete(`/users/${user.id}`
```
```react
import { router } from '@inertiajs/react'
router.delete(`/users/${user.id}`
```
```svelte
import { router } from '@inertiajs/svelte'
router.delete(`/users/${user.id}`
```
--------------------------------
### React Split Auth Layout Example
Source: https://laravel.com/starter-kits
Illustrates the usage of a split-view authentication layout component in a React and Inertia.js environment. This highlights the flexibility in designing authentication interfaces.
```typescript
import AuthLayoutTemplate from '@/layouts/auth/auth-split-layout';
export default function AuthLayout({}) {
return ;
}
```
--------------------------------
### Global Title Modification with createInertiaApp Setup (JavaScript)
Source: https://context7_llms
Explains how to globally modify page titles using the `title` callback within the `createInertiaApp` setup method in JavaScript. This is typically used for tasks like appending an application name to every page title.
```js
createInertiaApp({
title: title => \
// Appending app name to title
// Example: return `${title} - My App`
})
```
--------------------------------
### React Card Auth Layout Example
Source: https://laravel.com/starter-kits
Provides an example of integrating a card-style authentication layout in a React application with Inertia.js. This showcases one of the configurable layout options available in the starter kits.
```typescript
import AuthLayoutTemplate from '@/layouts/auth/auth-card-layout';
export default function AuthLayout({}) {
return ;
}
```
--------------------------------
### Make a GET Request with Axios
Source: https://github.com/axios/axios
Provides examples of making a GET request using Axios, demonstrating both direct parameter passing and using the `params` config object. It includes `.then()`, `.catch()`, and `.finally()` for handling asynchronous responses and errors.
```javascript
axios.get('/user?ID=12345')
.then(function (response) {
// handle success
console.log(response);
})
.catch(function (error) {
// handle error
console.log(error);
})
.finally(function () {
// always executed
});
```
```javascript
axios.get('/user', {
params: {
ID: 12345
}
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
})
.finally(function () {
// always executed
});
```
--------------------------------
### React Sidebar App Layout Example
Source: https://laravel.com/starter-kits
Shows how to implement a sidebar layout for the main application area using React and Inertia.js. This is a common layout pattern for dashboards and complex applications.
```typescript
import AppLayoutTemplate from '@/layouts/app/app-sidebar-layout';
export default function AppLayout({}) {
return ;
}
```
--------------------------------
### React Header App Layout Example
Source: https://laravel.com/starter-kits
Demonstrates the integration of a header-based layout for the application's main content using React with Inertia.js. This provides an alternative to sidebar navigation.
```typescript
import AppLayoutTemplate from '@/layouts/app/app-header-layout';
export default function AppLayout({}) {
return ;
}
```
--------------------------------
### Clone Repository
Source: https://github.com/prestancedesign/pingcrm-clojure
Clones the project repository from GitHub. This is the initial step to get the project files locally.
```bash
git clone https://github.com/prestancedesign/clojure-inertia-pingcrm-demo
cd clojure-inertia-pingcrm-demo
```
--------------------------------
### Register Inertia 'start' Event Listener via Native Browser Events
Source: https://context7_llms
Shows how to listen for Inertia 'start' events using the browser's native `addEventListener`, prepending 'inertia:' to the event name. This is an alternative to using `router.on()` and works across Vue, React, and Svelte.
```vue
import { router } from '@inertiajs/vue3'
document.addEventListener('inertia:start', (event) => {
console.log(`Starting a visit to ${event.detail.visit.url}`)
})
```
```react
import { router } from '@inertiajs/react'
document.addEventListener('inertia:start', (event) => {
console.log(`Starting a visit to ${event.detail.visit.url}`)
})
```
```svelte
import { router } from '@inertiajs/svelte'
document.addEventListener('inertia:start', (event) => {
console.log(`Starting a visit to ${event.detail.visit.url}`)
})
```
--------------------------------
### Browser Setup for Mocha
Source: https://mochajs.org/
Provides a basic HTML structure to run Mocha tests in a web browser. It includes setting up the BDD interface, checking for leaks, and running the tests.
```html
Mocha Tests
```
--------------------------------
### Vue: Importing and Using Components from a Single File
Source: https://vuejs.org/api/sfc-script-setup.html
Demonstrates how to import multiple components exported from a single file in Vue using the namespace import syntax. This is useful for organizing related components.
```vue
import * as Form from './form-components'
```
--------------------------------
### Preserve State on GET Request (Vue, React, Svelte)
Source: https://context7_llms
Instructs Inertia to preserve the component's state when using the `get` method. This is useful for maintaining form data or other local states across requests. The `router` object from the respective framework's Inertia adapter is used.
```javascript
import { router } from '@inertiajs/vue3'
router.get('/users', { search: 'John' }, { preserveState: true })
```
```javascript
import { router } from '@inertiajs/react'
router.get('/users', { search: 'John' }, { preserveState: true })
```
```javascript
import { router } from '@inertiajs/svelte'
router.get('/users', { search: 'John' }, { preserveState: true })
```
--------------------------------
### Running Mocha with a Setup File (Serial Mode)
Source: https://mochajs.org/
Command to execute Mocha tests using a specific setup file that contains root hooks. In serial mode, the specified setup file runs first, and its hooks are applied to all discovered test files. This approach is not compatible with parallel mode.
```bash
mocha --file "./test/setup.js" "./test/**/*.spec.js"
```
--------------------------------
### PHPUnit Configuration Example
Source: https://github.com/tbreuss/pingcrm-mithril
An example of a PHPUnit configuration file, typically named 'phpunit.xml'. This file defines settings for running PHPUnit tests, such as bootstrap files and test suites.
```xml
./tests/Unit./tests/Feature./app
```
--------------------------------
### Vue Client-Side Hydration Setup
Source: https://context7_llms
Updates the `ssr.js` file to use `createSSRApp` for enabling client-side hydration in Vue 3 applications with Inertia.js.
```diff
- import { createApp, h } from 'vue'
+ import { createSSRApp, 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) })
+ createSSRApp({ render: () => h(App, props) })
.use(plugin)
.mount(el)
},
})
```
--------------------------------
### Initialize Inertia App with Vue
Source: https://inertiajs.com/client-side-setup
Initializes the Inertia app using Vue 3. This involves creating a Vue app instance, importing necessary functions from Vue and Inertia, and configuring the `createInertiaApp` function with component resolution and setup callbacks.
```javascript
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)
},
})
```
--------------------------------
### React Client-Side Hydration Setup
Source: https://context7_llms
Modifies the `ssr.js` file to use `hydrateRoot` instead of `createRoot` for enabling client-side hydration in React applications with Inertia.js.
```diff
import { createInertiaApp } from '@inertiajs/react'
- import { createRoot } from 'react-dom/client'
+ import { hydrateRoot } 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()
+ hydrateRoot(el, )
},
})
```
--------------------------------
### Root Hook with Conditional Skipping
Source: https://mochajs.org/
An example of a root hook (`beforeAll`) that conditionally skips all tests if the current username is 'bob'. It utilizes the `os` module to get user info.
```javascript
// test/hooks.mjs
export const mochaHooks = {
beforeAll() {
// skip all tests for bob if (require("os").userInfo().username === "bob") {
return this.skip();
}
},
};
```
--------------------------------
### Including Setup File in Each Test (Workaround)
Source: https://mochajs.org/
A workaround for using root hooks in parallel mode by explicitly requiring or importing a setup file at the beginning of each test file. This avoids the boilerplate of defining hooks in every file but is generally less preferred.
```javascript
// In each test file:
// require('./setup.js')
// or
// import './setup.js'
```
--------------------------------
### Install SSR Dependencies - React
Source: https://context7_llms
No additional dependencies are required for server-side rendering when using the Inertia.js React adapter. The necessary packages are typically included by default.
```javascript
// No additional dependencies required
```
--------------------------------
### Build Assets and Configure Application (Bash)
Source: https://github.com/zgabievi/pingcrm-svelte
This snippet details the steps to build the application's frontend assets using npm and configure the Laravel environment. It involves copying the example environment file, generating an application key, and creating the SQLite database.
```bash
npm run dev
cp .env.example .env
php artisan key:generate
touch database/database.sqlite
```
--------------------------------
### Install PHP and NPM Dependencies
Source: https://github.com/inertiajs/pingcrm-svelte
Installs the necessary PHP dependencies using Composer and Node.js dependencies using npm. Ensure you have Composer and Node.js (with npm) installed.
```bash
composer install
npm ci
```
--------------------------------
### Shortcut Inertia Request Methods (GET, POST, PUT, PATCH, DELETE, RELOAD)
Source: https://context7_llms
Provides examples of using Inertia's shortcut request methods (`router.get`, `router.post`, `router.put`, `router.patch`, `router.delete`, and `router.reload`) in Vue, React, and Svelte. These methods offer a more concise way to perform common navigation actions, accepting URL, data, and options arguments. The `router.reload()` method is specifically for refreshing the current page's data with preserved state and scroll position. Dependencies include the respective Inertia adapters.
```javascript
import { router } from '@inertiajs/vue3'
router.get(url, data, options)
router.post(url, data, options)
router.put(url, data, options)
router.patch(url, data, options)
router.delete(url, options)
router.reload(options) // Uses the current URL
```
```javascript
import { router } from '@inertiajs/react'
router.get(url, data, options)
router.post(url, data, options)
router.put(url, data, options)
router.patch(url, data, options)
router.delete(url, options)
router.reload(options) // Uses the current URL
```
```javascript
import { router } from '@inertiajs/svelte'
router.get(url, data, options)
router.post(url, data, options)
router.put(url, data, options)
router.patch(url, data, options)
router.delete(url, options)
router.reload(options) // Uses the current URL
```
--------------------------------
### Clearing Form Errors (Vue, React, Svelte)
Source: https://context7_llms
Provides code examples for clearing form validation errors in Inertia.js. The `clearErrors()` method can be used to clear all errors or errors for specific fields. This is essential for resetting the form's error state after user interaction or successful submission. Examples are shown for Vue, React, and Svelte.
```js
// Clear all errors...
form.clearErrors()
// Clear errors for specific fields...
form.clearErrors('field', 'anotherfield')
```
```js
const { clearErrors } = useForm({ ... })
// Clear all errors...
clearErrors()
// Clear errors for specific fields...
clearErrors('field', 'anotherfield')
```
```js
// Clear all errors...
$form.clearErrors()
// Clear errors for specific fields...
$form.clearErrors('field', 'anotherfield')
```
--------------------------------
### React Auth Layout Example
Source: https://laravel.com/starter-kits
Demonstrates how to import and use a simple authentication layout component within a React application using Inertia.js. This snippet is part of the starter kit's layout customization options.
```typescript
import AuthLayoutTemplate from '@/layouts/auth/auth-simple-layout';
export default function AuthLayout({}) {
return ;
}
```
--------------------------------
### Svelte 4 Client-Side Hydration Setup
Source: https://context7_llms
Enables client-side hydration in Svelte 4 applications by setting the `hydrate` option to `true` within the `ssr.js` file for Inertia.js.
```diff
import { createInertiaApp } from '@inertiajs/svelte'
createInertiaApp({
resolve: name => {
const pages = import.meta.glob('./Pages/**/*.svelte', { eager: true })
return pages[`./Pages/${name}.svelte`]
},
setup({ el, App, props }) {
- new App({ target: el, props })
+ new App({ target: el, props, hydrate: true })
},
})
```
--------------------------------
### React: Implement Nested Persistent Layouts
Source: https://context7_llms
Provides an example of using nested persistent layouts in React with Inertia.js. The layout is structured with a parent and child layout component.
```jsx
import SiteLayout from './SiteLayout'
import NestedLayout from './NestedLayout'
const Home = ({ user }) => {
return (
Welcome
Hello {user.name}, welcome to your first Inertia app!
)
}
Home.layout = page => (
)
export default Home
```
--------------------------------
### Seed Database and Run Dev Server
Source: https://github.com/inertiajs/pingcrm-svelte
Populates the database with seed data and starts the local development server using Artisan. The output will provide the server address.
```bash
php artisan db:seed
php artisan serve
```