【问题标题】:Laravel route() pass dataLaravel route() 传递数据
【发布时间】:2021-06-21 16:33:54
【问题描述】:

我正在使用 Laravel 8 编写博客,但遇到了问题。

我希望用户能够对帖子发表评论。这样做我会存储他们评论的帖子的 ID。

这是我的评论表单:

<form method="POST" action="{{ route('comment.store', $post )}}">
            @csrf
            <div class="form-group">
                <textarea name="kommentar" class="form-control" rows="3"></textarea>
            </div>
            <button type="submit" class="btn btn-primary">Submit</button>
        </form>

我的控制器方法来存储评论:

    public function store(Request $request, $postid)
{
    $comment = new Comment();
    $comment->author = Auth::user()->name;
    $comment->text = $request->input('kommentar');
    $comment->post_id = $postid;
    $comment->save();

    return redirect('/post/'$postid );
}

还有我的 web.php:

Route::resource('comment', CommentController::class);

我想使用 route() 辅助函数,因为我希望以后能够更改 URL,而不必到处更改。我不知道如何传递表单数据和帖子 ID,以便我可以存储评论所属的帖子。

提前致谢。

【问题讨论】:

    标签: php laravel forms routes controller


    【解决方案1】:

    您可以通过 hidden 字段从您的视图中传递 post id 并使用 laravel Request 从您的 Controller store 方法接收它。

    查看

    <form method="POST" action="{{ route('comment.store') }}">
        @csrf
        <input type="hidden" name="post_id" value="{{ $post_id }}">
        <div class="form-group">
            <textarea name="kommentar" class="form-control" rows="3"></textarea>
        </div>
        <button type="submit" class="btn btn-primary">Submit</button>
    </form>
    

    路线

    Route::resource('comment', CommentController::class);
    
    

    控制器

    public function store(Request $request) {
        $comment = new Comment();
        $comment->author = Auth::user()->name;
        $comment->text = $request->kommentar;
        $comment->post_id = $request->post_id;
        $comment->save();
    
        return redirect('/post/' .$request->post_id );
    }
    

    【讨论】:

    • 我复制了你的代码,不幸的是 id 对我不起作用。我试图通过添加 dd($request->post_id); 来添加 postid;在 save 方法之前,它返回 null。
    • 检查$post 变量上的view 部分。 dd($post) 值有没有?
    • 当我在视图中添加 {{dd($post)}} 时,它会返回一个帖子
    • 那么,你的post_id 是什么?
    • 将您返回的post 中的post_id 设置为您的$post 变量。
    猜你喜欢
    • 2019-12-02
    • 1970-01-01
    • 2015-09-15
    • 2018-07-23
    • 1970-01-01
    • 2020-12-31
    • 2016-07-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多