Laravel 5.8编辑帖子会导致404错误

问题描述 投票:0回答:2

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

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

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

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

php laravel-5.8
2个回答
1
投票

您可以如下设置路线名称

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

0
投票

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

© www.soinside.com 2019 - 2024. All rights reserved.