0

我有一个简单的博客,其中包含 Post 资源和 Comment 嵌套资源。到目前为止,我可以看到属于帖子的所有评论并为帖子创建新评论。

我想提供删除特定评论的可能性,但不知何故我犯了一些错误。

这是comments.index包含所有评论的视图:

@extends('master')

@section('blog')

@foreach($comments as $comment)
  <div class="span11 well">
    <ul>
        <li><strong>Body: </strong> {{ $comment->body }} </li>
        <li><strong>Author: </strong> {{ $comment->author }}</li>
    </ul>

{{ Form::open(array('method' => 'DELETE', 'route' => array('posts.comments.destroy', $post_id), $comment->id)) }}

{{ Form::submit('Delete', array('class' => 'btn btn-danger')) }}

{{ Form::close() }}

 </div>
@endforeach
{{ link_to_route('posts.index', 'Back to Post index') }}

这是我运行索引时遇到的错误:路由“posts.comments.destroy”的参数“comments”必须匹配“[^/]++”(“”给定)以生成相应的 URL。

这是 CommentsController 中的 Index 方法:

public function index($post_id)
{
    $comments = Post::find($post_id)->comments;
    return View::make('comments.index', compact('comments'))->with('post_id', $post_id);
}

这是 CommentsController 中的 Destroy 方法:

public function destroy($post_id, $comment_id)
{
    $comment = $this->comment->find($comment_id)->delete();

    return Redirect::route('posts.comments.index', $post_id);
}

有人可以告诉我我在哪里犯了错误?

这是路线:

Route::resource('posts', 'PostsController');
Route::resource('posts.comments', 'CommentsController');
4

2 回答 2

2

您已在路线上放置了一个正则表达式测试器,以检查您的comments参数。
此错误消息表明您提供给 Laravel 的参数不好。

如果您的参数只是一个十进制 id,请改用正则\d+表达式。

于 2013-08-16T07:43:51.113 回答
0

如果没有您的 routes.php 文件 - 我不能确定,但​​我认为这可能是问题所在。

改变

{{ Form::open(array('method' => 'DELETE', 'route' => array('post.comments.destroy', $post_id), $comment->id)) }

{{ Form::open(array('method' => 'DELETE', 'route' => array('post.comments.destroy', array ($post_id, $comment->id))) }

如果这不起作用 - 请发布您的 routes.php 文件。

编辑:您已将路线定义为“资源”。这意味着您的销毁路线仅使用一个变量定义。您实际上不需要包含 $post,因此只需定义以下内容:

{{ Form::open(array('method' => 'DELETE', 'route' => array('posts.comments.destroy', $comment->id))) }}

并将您的销毁方法更改为此 - $post 无需删除 $comment:

public function destroy($comment_id)
{
    $comment = $this->comment->find($comment_id)->delete();

    return Redirect::back();
}
于 2013-08-16T07:44:22.387 回答