Laravel route() 传递数据
Laravel route() pass data
我在 Laravel 8 写博客,我 运行 遇到了问题。
我希望用户能够对 post 发表评论。这样做我会存储他们正在评论的 post 的 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 而不必在任何地方更改它。我不知道如何传递表单数据和 post id,所以我可以存储评论所属的 post。
提前致谢。
您可以通过 hidden
字段从您的视图中传递 post id
并使用 laravel [=17= 从您的 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 );
}
我在 Laravel 8 写博客,我 运行 遇到了问题。
我希望用户能够对 post 发表评论。这样做我会存储他们正在评论的 post 的 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 而不必在任何地方更改它。我不知道如何传递表单数据和 post id,所以我可以存储评论所属的 post。
提前致谢。
您可以通过 hidden
字段从您的视图中传递 post id
并使用 laravel [=17= 从您的 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 );
}