Laravel 5.8 编辑 Post 导致 404 错误

Laravel 5.8 Editing a Post results in 404 error

我在我的应用程序中添加了数据表,我想将每个条目的 ID 设为指向编辑页面的超链接,以便用户能够编辑他们的 Post。但是我收到 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'));
    }

我尝试在线搜索并尝试调整我的路线,但我设法让事情变得更糟,而不是解决我的问题。非常感谢任何帮助!

您确定您的数据库中有一条记录与 get 方法附带的 $id 匹配吗?如果没有匹配的记录,findOrFail($id) returns 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

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

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'));
}