简体   繁体   中英

Dynamic routes doesn't work in Laravel 5.5

I have some problem with dynamic routes.

I just tried add likes value in posts table to some post.

web.php

Route::get('post/{$id}/like', 'PostController@like')->name('post.like');
Route::resource('post', 'PostController');

And i define 1 custom method in resource controller PostControleler.

PostController@like

public function like($id)
{
    $post = Post::find($id);
    $post->likes++;
    $post->save();
    return redirect()->back();
}

and link in blade php view

<a href="{{route('post.like', $post)}}" class="btn btn-success btn-xs">Like</a>

When clicking on a link, nothing happen, just displayed 404

Sorry, the page you are looking for could not be found.

Why that dynamic route doesn't work.

PS

That code works if i replace method to show instead like (it means that the custom method is hindered by something, the code itself is working)

Thanks in advance.

you need to replace your href by this below and make shure if $post it's $post of id value or replace it with $post->id

<a href="{!! route('post.like', [$post]) !!}" class="btn btn-success btn-xs">Like</a>

and change get by post (here your are send data to the server that means you will post $id)

Route::post('/post/{$id}/like', 'PostController@like')->name('post.like');

Damn....i just forgot delete $ sign in custom route.

Should be:

Route::get('post/{post}/like', 'PostController@like')->name('post.like');

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