Laravel route with JavaScript

Today I am going to show you how you can write your route names inside javascript file. Laravel provides the flexible way to access your URL by using route name attribute.

Laravel Route with javascript


Same now we can use that route naming convention within our JavaScript code. How cool it is right !!

So here I am using Laravel 5.4. Basically, it’s a package called Ziggy. The Very powerful package that provides JavaScript functions to write route names instead of writing custom URLs.

To install package you can use this command or you can clone from GitHub too.

After installing the package you need to add a service provider to load service at app.php into config folder.

As we all know Laravel uses blade template engine to run HTML or Front Code. Here we need to add @route blade directive at the layout or any blade file where you want to use a feature of JavaScript route.

Here I am using default welcome.blade.php file which is cames when you install fresh Laravel setup. Also first you have to register your Laravel routes either it will throw an error.

Here I uses Laravel resources method. Behind the scene it will write 7 diffrent URLs for with route name also. That will look like this:

URL Route name
/posts -[GET] posts.index
/posts/create -[GET] posts.create
/posts/store -[POST]
/posts/{id}/edit -[GET] posts.edit
/posts/{id} -[PATCH] posts.update
/posts/{id} -[GET]
/posts/{id} -[DELETE] posts.destroy


As I specified Laravel provides default routing names. Now we can write any Route name and Laravel convert it as a URL.

Here is my welcome.blade.php file:


We should register @routes directive. Inside script tag, we need to write our JavaScript code.

route(‘route_name’); function will use you can pass parameter into second parameter. The method will return your object you need to get ‘url’ key to get your URL.

Remember if you do not register your route it will throw you an error. If you want to pass URL into Ajax or axios request just pass the whole object into a function like this:

You can pass a parameter into second argument of route method. like this:

You can use any method of above that I shows. Suppose you want to pass extra parameter you can use JavaScript Object notation as I shows in first example above snippet.

You can whitelist and blacklist your route. for that you need to create ziggy.php into config folder. Later on you can specify your routing like this:

it will allow all route with api prefix and block all route with admin prefix. For more information visit this.

Leave a Reply

Your email address will not be published. Required fields are marked *