Laravel 5 没有保存到数据库但是没有错误?
Laravel 5 It's not saving to database but there is no error?
我正在使用 laravel 5.5 并尝试将我的博客 post 的评论保存到数据库中。当我尝试这个时,它没有保存到数据库并且没有给出任何错误?
(我添加了一条新评论,点击发送,将我重定向到同一页面。但没有将评论保存到数据库..)
控制器
public function store(Request $request, $post_id)
{
$this->validate($request, [
'name' => 'required',
'email' => 'required',
'comment' => 'required'
]);
$post = Post::find($post_id);
$comment = new Comment;
$comment->name = $request->name;
$comment->email = $request->email;
$comment->comment = $request->comment;
$comment->approved = true;
$comment->posts()->associate($post);
$comment->save;
return redirect()->route('post_slug',$post->slug);
}
如果您没有保存评论并且被重定向到同一页面,我假设您没有填写 name
、email
或 comment
字段。这验证是如何工作的 - 如果失败,您将被重定向到之前的 url,因此请确保您显示验证错误以查看发生了什么。
编辑
还有一件事 - 你应该使用 ->save()
而不是 ->save
并在最后移动关联 post 所以而不是:
$comment->posts()->associate($post);
$comment->save;
你应该使用:
$comment->save();
$comment->posts()->associate($post);
使用事务将它们保存到数据库中可能是合理的。
当您使用 ->save
时,您实际上访问了模型的属性并且没有 运行 模型保存。
Laravel Eloquent 提供了将新模型添加到关系中的便捷方法,当您使用它时,使用 save() 方法它应该如下所示:
$comment = new App\Comment([
'name' => $request->name,
'email' => $request->email,
'comment' => $request->comment,
'approved' => true
]);
$post = App\Post::find($post_id);
$post->comments()->save($comment);
或者正确的方法是使用 create() 方法,它接受一个属性数组,创建一个模型,并将其插入到数据库中。例如:
$post = App\Post::find($post_id);
$comment = $post->comments()->create([
'name' => $request->name,
'email' => $request->email,
'comment' => $request->comment,
'approved' => true
]);
尝试将参数添加到 $fillable
我正在使用 laravel 5.5 并尝试将我的博客 post 的评论保存到数据库中。当我尝试这个时,它没有保存到数据库并且没有给出任何错误?
(我添加了一条新评论,点击发送,将我重定向到同一页面。但没有将评论保存到数据库..)
控制器
public function store(Request $request, $post_id)
{
$this->validate($request, [
'name' => 'required',
'email' => 'required',
'comment' => 'required'
]);
$post = Post::find($post_id);
$comment = new Comment;
$comment->name = $request->name;
$comment->email = $request->email;
$comment->comment = $request->comment;
$comment->approved = true;
$comment->posts()->associate($post);
$comment->save;
return redirect()->route('post_slug',$post->slug);
}
如果您没有保存评论并且被重定向到同一页面,我假设您没有填写 name
、email
或 comment
字段。这验证是如何工作的 - 如果失败,您将被重定向到之前的 url,因此请确保您显示验证错误以查看发生了什么。
编辑
还有一件事 - 你应该使用 ->save()
而不是 ->save
并在最后移动关联 post 所以而不是:
$comment->posts()->associate($post);
$comment->save;
你应该使用:
$comment->save();
$comment->posts()->associate($post);
使用事务将它们保存到数据库中可能是合理的。
当您使用 ->save
时,您实际上访问了模型的属性并且没有 运行 模型保存。
Laravel Eloquent 提供了将新模型添加到关系中的便捷方法,当您使用它时,使用 save() 方法它应该如下所示:
$comment = new App\Comment([
'name' => $request->name,
'email' => $request->email,
'comment' => $request->comment,
'approved' => true
]);
$post = App\Post::find($post_id);
$post->comments()->save($comment);
或者正确的方法是使用 create() 方法,它接受一个属性数组,创建一个模型,并将其插入到数据库中。例如:
$post = App\Post::find($post_id);
$comment = $post->comments()->create([
'name' => $request->name,
'email' => $request->email,
'comment' => $request->comment,
'approved' => true
]);
尝试将参数添加到 $fillable