How to setup Ziggy on Laravel/Inertija/Vite/Vue
--
The good thing about the Ziggy documentation in the repo, is that its very detailed and tries to cover all scenarios.
The downside of this documentation, is that is hard to find the right instructions for your specific environment.
Here is the setup if you on a fresh Laravel 9 application together with Vite, Vue, Intertija. Roadmap:
- Install composer package
- Add @routes helper in your blade.
- Add ziggy-js alias
- Load ZiggyVue
- Celebrate
Let’s go into details:
Install composer Package
Install like this (no npm package or anything else required):
composer require tightenco/ziggy
Add @routes helper
<!DOCTYPE html>
<html class="h-full bg-white">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0" />
@vite(['resources/assets/css/tailwindcore.css', 'resources/assets/js/tailwind-colorful/dashboard/app.js'])
@routes
@inertiaHead
</head>
<body class="h-full">
@inertia
</body>
</html>
Add ziggy-js alias
First, this is how the vite.config.js should look like:
// vite.config.js
import { defineConfig } from 'vite';
import laravel from 'laravel-vite-plugin';
import vue from '@vitejs/plugin-vue';
import path from 'path';
export default defineConfig({
resolve: {
alias: {
'ziggy-js': path.resolve('vendor/tightenco/ziggy/dist/vue.es.js'),
}
},
plugins: [
laravel({
input: [
'resources/assets/css/tailwindcore.css',
'resources/assets/js/tailwind-colorful/dashboard/app.js',
]
}),
// react(),
vue({
template: {
transformAssetUrls: {
base: null,
includeAbsolute: false,
},
},
}),
],
});
Import ZiggyVue
This is my app.js:
import { createApp, h } from 'vue'
import { createInertiaApp } from '@inertiajs/vue3'
import UserMaster from './Layout/UserMaster.vue';
import AdminMaster from './Layout/AdminMaster.vue';
import { ZiggyVue } from 'ziggy-js';
createInertiaApp({
resolve: name => {
const pages = import.meta.glob('./Pages/**/*.vue', { eager: true })
const page = pages[`./Pages/${name}.vue`];
const Layout = name.startsWith('AdminDashboard') ? AdminMaster : UserMaster;
page.default.layout = page.default.layout || Layout;
return page;
},
setup({ el, App, props, plugin }) {
const VueApp = createApp({ render: () => h(App, props) })
.use(plugin)
.use(ZiggyVue)
.mount(el)
},
})
And that is the entire setup. You can use “route” helper anywhere within your Vue components, without importing it.
Also be aware, there is no need to run `php artisan ziggy:generate` as descriped in the docs.