I'm using laravel 5.5 and try to save my blog post's comments to the database. When I tried this, it's not saving to database and not give any error?
(I add a new comment, click send, redirect me same page. But not save comment to database..)
Controller
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);
}
If you don't have comment saved and you are redirected to same page, I assume you don't have name
, email
or comment
fields filled in. This is how validation works - if it fails, you will be redirected to previous url, so make sure you are displaying errors from validation to see what's going on.
EDIT
And one more thing - instead of ->save
you shuould use ->save()
and move associating post at the end so instead of:
$comment->posts()->associate($post);
$comment->save;
you should use:
$comment->save();
$comment->posts()->associate($post);
and probably it's reasonable to use transaction to save those into database.
When you used ->save
you actually accessed attribute of model and haven't run model saving.