Support the ongoing development of Laravel.io →
Input Blade Laravel.io

Hi all! I wanna know is there any way to access to laravel route in javascript. For example I have this button:

<a onclick="deletePost({!! $post->id !!});" class="btn btn-default">Delete</a>

and JS:

function deletePost(post_id) {
  bootbox.confirm("Are you sure?", function(result) {
  if (result) {
    document.location.href="{!! route('delete_post', post_id); !!}";
  }
}

All principle is that then I press on a button it calls for deletePost method in javascript with post id, javascript using bootbox shows dialog box to confirm if you really wanna delete it. If you confirmed it should redirect you to route where controller deleting post. So how I can do that if it is possible. Currently this redirects me to:

.../{!! route('delete_post', post_id); !!}
Last updated 3 years ago.
0

Hi Destructor,

As long as this javascript is within blade it should work just fine, meaning, your code must be inline script.

Another way to go about is, define that url you want to use in your blade view and call it in external javascript. e.g.

At the head of my blade view i would have this:

  <script type="text/javascript">
	 	var deletePostUri = "{{ route('delete_post',$post_id)}}";
	</script>

Now deletePostUri is globally defined within that page, any javascript inline or external that is loaded after will have access to it.

I hope that helps.

Thanks

Last updated 9 years ago.
0

Thanks for help :)

0

Isn't it vulnerable to CSRF?

0

Sign in to participate in this thread!

PHPverse

Your banner here too?

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2025 Laravel.io - All rights reserved.