我一直在从事laravel 5.7博客项目。我想评论一篇文章。
我需要实现这一目标:
我的评论控制器在这里:
public function __construct()
{
$this->middleware('auth');
}
public function store(Post $post) {
$comment = Comment::create([
'body' => session('comment')?:request('body'),
'post_id' => $post->id,
'user_id' => auth()->user()->id
//before logging in, you don't have an user_id yet.
]);
return back()->with('success', 'Add comment succeeded');
}
web.php此处路由:
Route::post('/posts/{post}/comments', 'CommentsController@store')->name('addComment');
基本上,身份验证中间件拦截了我的表单数据提交,我想与表单数据一起访问身份验证中间件。登录后没有丢失它们。
答案 0 :(得分:1)
这里是解决方案。有点棘手。在进入auth中间件之前先将注释保存到会话中。登录后,获取该路由以创建注释。 路线:
Route::get('/posts/{post}/comments', 'CommentsController@store')->name('addComment');
Route::post('/posts/{post}/comments', 'CommentsController@commentSave');
评论控制器:
public function __construct()
{
$this->middleware('auth', ['except' => ['commentSave']]);
}
public function commentSave(Request $request){
$url = \URL::previous();
session(['comment' => $request->input('body')]);
return redirect("$url/comments");
}
public function store(Post $post){
if(session('comment')){
$comment = Comment::create([
'body' => session('comment'),
'post_id' => $post->id,
'user_id' => auth()->user()->id
]);
session(['comment' => null]);
return redirect("posts/$post->id")->with('success', 'Add comment succeeded');
}
return redirect("posts/$post->id");
}
答案 1 :(得分:0)
我认为您的问题的解决方案在这里: https://laravel.com/docs/5.7/session#storing-data