我的laravel try-catch语句不起作用

时间:2018-12-20 20:04:43

标签: laravel try-catch

这里,我在发布控制器中有一个简单的laravel代码,用于存储发布。我想拥有唯一的标题。因此,我将数据库中的标题设置为唯一。在下面的代码中,我有一个try-catch语句。但是,当我创建标题重复的帖子时,出现错误(显示 laravel错误页面),并且catch不会调用!我不知道为什么,我有点困惑。有人可以帮我吗?

    $post = Post::create([
        'title' => $request->title,
        'content' => $request->content,
        'category_id' => $request->category
    ]);
    try {
        $post->save();
        Session::flash('success', 'New post created successfully.');
    }
    catch (\Exception $e)
    {
        Session::flash('success', $e->getMessage());
    } 
return redirect()->route('post.index');

laravel错误页面说:

  

Illuminate \ Database \ QueryException(23000)SQLSTATE [23000]:   违反完整性约束:1062密钥的重复条目“ T3”   'posts_title_unique'(SQL:插入poststitlecontent,   category_idupdated_atcreated_at)值(T3,kj; k,,   2018-12-20 19:53:52,2018-12-20 19:53:52))

我要向用户显示此错误。所以我用了try-catch语句。但似乎无法正常工作。 在此链接中,try-catch应该有效:Laravel Model->save() returns false but no error。我也用catch来管理其他可能发生的错误

1 个答案:

答案 0 :(得分:4)

问题是您正在Post::create()块之外使用try-catchcreate()函数不仅会在内存中创建模型实例,还会在新创建的实例上调用save(),从而使对save()的显式调用变得多余。

您真正想要的是在new Post(...)块内使用Post::create(...)try-catch

try {
    $post = Post::create([
        'title' => $request->title,
        'content' => $request->content,
        'category_id' => $request->category
    ]);
    Session::flash('success', 'New post created successfully.');
}
catch (\Exception $e)
{
    Session::flash('success', $e->getMessage());
} 
return redirect()->route('post.index');
相关问题