简体   繁体   English

Laravel 5 它没有保存到数据库但没有错误?

[英]Laravel 5 It's not saving to database but there is no error?

I'm using laravel 5.5 and try to save my blog post's comments to the database.我正在使用 laravel 5.5 并尝试将我的博客文章的评论保存到数据库中。 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.如果您没有保存评论并且您被重定向到同一页面,我假设您没有填写nameemailcomment字段。这就是验证的工作方式 - 如果失败,您将被重定向到以前的 url,因此,请确保您显示验证错误以查看发生了什么。

EDIT编辑

And one more thing - instead of ->save you shuould use ->save() and move associating post at the end so instead of:还有一件事 - 而不是->save你应该使用->save()并在最后移动关联的帖子,而不是:

$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.当您使用->save时,您实际上访问了模型的属性并且没有运行模型保存。

Laravel Eloquent provides convenient methods for adding new models to relationships, when you using it, with save() method it should look like that: 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);

Or the proper way is to use create() method which accepts an array of attributes, creates a model, and inserts it into the database.或者正确的方法是使用 create() 方法,该方法接受属性数组,创建模型并将其插入数据库。 For example:例如:

$post = App\Post::find($post_id);

$comment = $post->comments()->create([
'name' => $request->name,
'email' => $request->email,
'comment' => $request->comment,
'approved' => true
]);

尝试将参数添加到 $fillable

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM