Laravel Wayfinder Documentation

repository·main·Indexed 21 days ago

https://github.com/laravel/wayfinder

A bridge between Laravel backends and TypeScript frontends that automatically generates type-safe, importable TypeScript functions for controllers and routes. It eliminates hardcoded URLs and manual route syncing by providing a Vite plugin and the `wayfinder:generate` Artisan command to create definitions for actions and named routes, including support for Inertia.js integration and HTML form attribute generation.

Tokens
3.4K
Snippets
5
Records
19
Agent score
82%

What's inside Laravel Wayfinder

  1. Use Conventional Forms with Wayfinder

    main

    To use Wayfinder for HTML form attributes, you must first opt-in during generation:

    php artisan wayfinder:generate --with-form

    Then, use the .form() method to generate attributes for <form> elements.

    Basic Form

    import { store } from "@/actions/App/Http/Controllers/PostController";
    
    <form {...store.form()} />
    // Results in: <form action="/posts" method="post">

    Forms with Parameters and Method Spoofing

    For routes requiring parameters or method spoofing (like PATCH or PUT):

    import { update } from "@/actions/App/Http/Controllers/PostController";
    
    <form {...update.form(1)} />
    // Results in: <form action="/posts/1?_method=PATCH" method="post">

    Specifying a Method

    You can explicitly specify the method on the form helper:

    <form {...update.form.put(1)} />
  2. Install Wayfinder

    main

    To set up Wayfinder, install the Composer package and the Vite plugin to enable automatic TypeScript generation during development and builds.

    1. Install the backend package:
    composer require laravel/wayfinder
    1. Install the Vite plugin via NPM:
    npm i -D @laravel/vite-plugin-wayfinder
    1. Register the plugin in your vite.config.js:
    import { wayfinder } from "@laravel/vite-plugin-wayfinder";
    
    export default defineConfig({
        plugins: [
            wayfinder(),
            // ...
        ],
    });
  3. Deploy Wayfinder correctly

    main

    Wayfinder relies on the current Laravel route table. If you use php artisan optimize or route:cache during deployment, ensure you clear the route cache before regenerating definitions to avoid stale or missing routes.

    When using the Vite plugin, run the following sequence in your deployment script before npm run build:

    php artisan route:clear
    npm run build
  4. Integrate Wayfinder with Inertia.js

    main

    Wayfinder integrates seamlessly with Inertia.js components.

    Using with useForm

    You can pass the result of a Wayfinder action directly into the submit method of Inertia's useForm hook. It will automatically resolve the URL and method.

    import { useForm } from "@inertiajs/react";
    import { store } from "@/actions/App/Http/Controllers/PostController";
    
    const form = useForm({ name: "My Post" });
    form.submit(store()); // Automatically POSTs to the correct URL

    Pass the Wayfinder result directly to the href prop of the Link component:

    import { Link } from "@inertiajs/react";
    import { show } from "@/actions/App/Http/Controllers/PostController";
    
    <Link href={show(1)}>Show Post</Link>
    form.submit(store());
  5. Import Controllers and Named Routes

    main

    Importing Controllers

    You can import the entire controller object to call its methods. Note that importing the whole controller prevents tree-shaking.

    import PostController from "@/actions/App/Http/Controllers/PostController";
    
    PostController.show(1);

    Importing Named Routes

    You can import routes directly from the routes/ directory using their names.

    import { show } from "@/routes/post";
    
    // Named route is `post.show`...
    show(1); // { url: "/posts/1", method: "get" }

    Multiple Routes to the same Action

    If multiple routes point to the same controller method, the exported action becomes a dictionary keyed by the URI instead of a callable:

    import { index } from "@/actions/App/Http/Controllers/ClientPaymentsController";
    
    // Pick the specific URI:
    index["/clients/{client}/payments"]({ client: 1 });

    It is recommended to use the named route import instead to avoid this complexity.

  6. Manage Query Parameters

    main

    Wayfinder methods accept an optional options object as the final argument to handle query strings.

    Appending Query Parameters

    Use the query key to append parameters to the URL:

    show(1, { query: { page: 1, sort_by: "name" } });
    // { url: "/posts/1?page=1&sort_by=name", method: "get" }

    Merging with Existing Parameters

    Use mergeQuery to combine the new parameters with existing ones in the current URL (e.g., from window.location.search):

    // Current URL: ?page=1&sort_by=category&q=shirt
    show.url(1, { mergeQuery: { page: 2, sort_by: "name" } });
    // "/posts/1?page=2&sort_by=name&q=shirt"

    Removing Parameters

    To remove a parameter from the resulting URL, set its value to null or undefined within mergeQuery:

    // Current URL: ?page=1&sort_by=category&q=shirt
    show.url(1, { mergeQuery: { page: null } });
    // "/posts/1?sort_by=category&q=shirt"
  7. Use Wayfinder generated actions

    main

    Wayfinder functions (actions) return an object containing the resolved url and the HTTP method.

    Basic Usage

    import { show } from "@/actions/App/Http/Controllers/PostController";
    
    show(1); // { url: "/posts/1", method: "get" }

    Accessing specific properties

    You can call additional methods on the generated function to get specific outputs:

    • .url(args): Returns only the URL string.
    • .[method](args): Returns the object for a specific HTTP method (e.g., .head(), .get(), .post()).
    show.url(1); // "/posts/1"
    show.head(1); // { url: "/posts/1", method: "head" }

    Argument shapes

    Actions support several argument formats:

    • Single parameter: show(1) or show({ id: 1 })
    • Multiple parameters: update([1, 2]) or update({ post: 1, author: 2 }) or update({ post: { id: 1 }, author: { id: 2 } })
    • Parameter binding keys: If a route uses a specific binding like {post:slug}, you can pass it as an object: show({ slug: "my-post" }).

    Handling JavaScript reserved words

    If a controller method uses a JS reserved word (like delete), Wayfinder renames it to [methodName]Method (e.g., deleteMethod).

  8. Configure session and cache drivers

    main

    Manage user sessions and application caching:

    Sessions

    • SESSION_DRIVER: The driver used for sessions (e.g., cookie).
    • SESSION_LIFETIME: The number of minutes before a session expires.
    • SESSION_ENCRYPT: Whether session data should be encrypted.
    • SESSION_PATH: The session path.
    • SESSION_DOMAIN: The session domain.

    Cache

    • CACHE_STORE: The driver used for caching (e.g., database).
    • CACHE_PREFIX: A prefix for all cached keys.
  9. Configure database connections

    main

    Define your database connection settings:

    • DB_CONNECTION: The database driver to use (e.g., sqlite, mysql).
    • DB_HOST: The database server host.
    • DB_PORT: The database server port.
    • DB_DATABASE: The name of the database.
    • DB_USERNAME: The database username.
    • DB_PASSWORD: The database password.
  10. Configure mail and AWS services

    main

    Settings for external service integrations:

    Mail

    • MAIL_MAILER: The mail driver (e.g., log).
    • MAIL_HOST: The SMTP host.
    • MAIL_PORT: The SMTP port.
    • MAIL_USERNAME: The SMTP username.
    • MAIL_PASSWORD: The SMTP password.
    • MAIL_ENCRYPTION: The encryption protocol.
    • MAIL_FROM_ADDRESS: The default sender email address.
    • MAIL_FROM_NAME: The default sender name.

    AWS

    • AWS_ACCESS_KEY_ID: AWS access key.
    • AWS_SECRET_ACCESS_KEY: AWS secret key.
    • AWS_DEFAULT_REGION: The AWS region (e.g., us-east-1).
    • AWS_BUCKET: The S3 bucket name.
    • AWS_USE_PATH_STYLE_ENDPOINT: Boolean to enable path-style endpoints.
  11. Configure logging and error reporting

    main

    Control how the application handles logs and deprecation warnings using these variables:

    • LOG_CHANNEL: The primary logging channel (e.g., stack).
    • LOG_STACK: The specific stack to use if LOG_CHANNEL is set to stack.
    • LOG_DEPRECATIONS_CHANNEL: The channel used for reporting deprecations (set to null to disable).
    • LOG_LEVEL: The minimum logging level (e.g., debug).
  12. Configure Redis and Memcached

    main

    Settings for key-value store drivers:

    Redis

    • REDIS_CLIENT: The Redis client library (e.g., phpredis).
    • REDIS_HOST: The Redis server host.
    • REDIS_PASSWORD: The Redis server password.
    • REDIS_PORT: The Redis server port.

    Memcached

    • MEMCACHED_HOST: The Memcached server host.