How to configure a route With InertiaJs/ Laravel?

Updated: Feb 12, 2025

How to configure a route With InertiaJs/ Laravel?

To configure a route with Inertia.js and Laravel, you'll need to follow these steps:

  1. Define the route in Laravel:

First, you need to define the route in your Laravel application. You can define the route in the routes/web.php file or in a route file if you prefer to keep your routes organized. Here's an example of defining a route in routes/web.php:

Route::get('/dashboard', 'DashboardController@index')->name('dashboard.index');

In this example, we're defining a GET route to the /dashboard URL, which will be handled by the DashboardController@index method. We've also given the route a name of dashboard.index.

  1. Create the Inertia component:

Next, you need to create an Inertia component for the route. Inertia components are Vue.js components that use Laravel's server-side rendering to fetch data and render the component's view. Here's an example of creating an Inertia component:

import { defineComponent } from 'vue'
import { Head, Link } from '@inertiajs/inertia-vue'

export default defineComponent({
  setup() {
    return {
      props: {},
    }
  },
  components: {
    Head,
    Link,
  },
})

In this example, we're defining a new Vue.js component called Dashboard.vue. We're importing the defineComponent function from Vue.js, as well as the Head and Link components from Inertia.js. We're also defining an empty props object and an empty components object.

  1. Fetch data with Inertia:

Next, you need to fetch data from your Laravel application and pass it to the Inertia component. You can do this by defining a method in the component that uses Inertia's usePage function to fetch the data. Here's an example:

import { defineComponent, usePage } from 'vue'
import { Head, Link } from '@inertiajs/inertia-vue'

export default defineComponent({
  setup() {
    const { data } = usePage()

    return {
      data,
    }
  },
  components: {
    Head,
    Link,
  },
})

In this example, we're using Inertia's usePage function to fetch the data for the component. The data will be passed to the component as a data property.

  1. Render the component:

Finally, you need to render the component in your Laravel view. You can do this by returning the component from the controller method that handles the route. Here's an example:

use App\Http\Components\Dashboard;

public function index()
{
    return (new Dashboard)->render();
}

In this example, we're importing the Dashboard component and returning it from the index method of the DashboardController. Inertia will automatically render the component and send the data to the client-side component.

That's it! You've now configured a route with Inertia.js and Laravel. Your component will be able to fetch data from the server and render the view dynamically.