简体   繁体   中英

How to pass Vue.js variable to Laravel Blade route helper

For example, I have a link to an other post like this in my template

<a href="{{ route('post', ['post' => @{{ post.id }}]) }}">My post</a>

I want to be able to use the post object within the route helper to use the id.

Is there any syntax for this use case?

Or is there an other way of doing this?

Actually I had similar problems to solve this kind of cases. Your question related with Vue exactly, but the method below you can use for your case as well. Anyway you can't execute JS and PHP at the same time, cuz they're working at different sides. But as I also liked to have all routes with their aliases, I thought this approach.. You can imitate something like this:

Route::get('/', 'PostController@all')->name('all'); // all posts page
Route::get('post', 'PostController@all')->name('all_page'); // THIS IS THE THING (one additional route), WHICH WILL TAKE RESPONSIBILITY ON CASE, WHEN post_id WILL BE EMPTY
Route::get('post/{post_id}', 'PostController@post')->name('post');

This method will allow you to use the 1st and 3rd routes as normally, and as mixed too in the different places on your app like this:

{{ route('post.all') }}
{{ route('post', ['post' => $post_id]) }}
{{ route('post') }}/@{{ post.id }}

In scripts you can implement the approach like this:

let someUrl = "{{ route('post') }}/" + postObj.id;

In the view you can implement the method like this:

<a href="{{ route('post') }}/@{{ post.id }}">My post @{{ post.id }}</a>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM