How To Use Laravel Route In Javascript File

Hello Artisan, now i am going to show you that how to use your Laravel routes in JavaScript. To do this i will use tighten/ziggy packages. Ziggy provides a JavaScript route() helper function that works like Laravel's, making it easy to use your Laravel named routes in JavaScript.

It very simple and easy to install and setup. Just you have to run composer command to install it and then all will be set to go. Using this package we can use Laravel route in our JavaScript file. Hope this package will be very helpful for you. Let's see how to use laravel call route from javascript. 

Install Ziggy

To install ziggy run below command

composer require tightenco/ziggy

 

Now after installation you have to add the @routes Blade directive to your main layout (before your application's JavaScript), and the route() helper function will now be available globally!

Usage

Ziggy's route() helper function works like Laravel's—you can pass it the name of one of your routes, and the parameters you want to pass to the route, and it will return a URL.

// routes/web.php

Route::get('posts', fn (Request $request) => /* ... */)->name('posts.index');

 

Now in you js file

// app.js

route('posts.index'); // 'https://ziggy.test/posts'

 

With parameters

// routes/web.php

Route::get('posts/{post}', fn (Request $request, Post $post) => /* ... */)->name('posts.show');

 

And then in your JavaScript file

// app.js

route('posts.show', 1);           // 'https://ziggy.test/posts/1'
route('posts.show', [1]);         // 'https://ziggy.test/posts/1'
route('posts.show', { post: 1 }); // 'https://ziggy.test/posts/1'

 

Hope it can help you. For more information you can visit tighten/ziggy

 

#laravel #laravel-packages #tightenziggy