Laravel 5.8编辑帖子导致404错误

我在我的应用程序中添加了数据表,我希望使每个条目的ID成为指向编辑页面的超链接,以便用户能够编辑其帖子。但是我收到404 Not Found错误

我尝试更新路由文件,但没有得到正确的结果,我无法弄清楚自己在做什么错

我的网络php文件具有:

Route::get('edit','PostsController@edit');

我的帖子的索引是

<table class="display" id="postsTable">
    <thead>
    <tr>
        <td>ID</td>
        <th>Title</th>
        <th>Slug</th>
        <th>Subtitle</th>
        <th>Content</th>
        <th>Category</th>
    </tr>
    </thead>
    <tbody>
    @foreach($posts as $post)
        <tr>
            <td><a href="edit/{{$post->id}}">{{$post->id}}</a></td>
            <td>{{$post->title}}</td>
            <td>{{$post->slug}}</td>
            <td>{{$post->subtitle}}</td>
            <td>{{$post->content}}</td>
            <td>{{$post->category_id}}</td>
        </tr>
      @endforeach
    </tbody>

而PostsController编辑功能是:

  public function edit($id)
    {
        $posts = Post::findOrFail($id);
        return view('posts.edit',compact('posts'));
    }

我尝试在线搜索并尝试一些路线,但我设法使事情变得更糟,而不是解决了我的问题。任何帮助深表感谢!

huanghelou007 回答:Laravel 5.8编辑帖子导致404错误

您可以如下设置路线名称

Route::get('edit/{id}','PostsController@edit')->name('edit_post');

然后在HTML部分中按如下所述使用它

<tbody>
@foreach($posts as $post)
    <tr>
        <td><a href="{{ route('edit_post',$post->id) }}">Edit Post</a></td>
        <td>{{$post->title}}</td>
        <td>{{$post->slug}}</td>
        <td>{{$post->subtitle}}</td>
        <td>{{$post->content}}</td>
        <td>{{$post->category_id}}</td>
    </tr>
  @endforeach
</tbody>

您应该在客户端添加一些验证,以确保您具有数据,以便在出现以下情况时可以在其中添加代码

@if ($posts ?? count($posts) ?? false)
    // Your code here
@endif
,

您确定数据库中有一条记录与get方法附带的$ id相匹配吗?如果没有匹配的记录,则findOrFail($ id)返回404页。

,

在控制器检查中,是否找到了帖子

public function edit($id)
{
    $posts = Post::findOrFail($id);
    // check post are found or not
    if(!isset($posts)){
         # show your errors if data not found
    }
    return view('posts.edit',compact('posts'));
}
本文链接:https://www.f2er.com/3131285.html

大家都在问