【问题标题】:My laravel try-catch statements doesn't work我的 laravel try-catch 语句不起作用
【发布时间】:2018-12-20 20:04:43
【问题描述】:

在这里,我在 post 控制器中有一个简单的 laravel 代码,用于存储帖子。我想拥有独特的头衔。所以我将数据库中的标题设置为唯一的。在下面的代码中,我有一个 try-catch 语句。但是当我创建一个标题重复的帖子时,我会出错(laravel error page shown)并且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: 插入posts (title, content, category_id, updated_at, created_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 来管理其他可能发生的错误

【问题讨论】:

  • 尝试使用dd($request->all()); 来查看请求中的内容是否正确。 laravel 错误页面是怎么说的?
  • @Brunaine laravel 错误页面显示:SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry 'T3' for key 'posts_title_unique' (SQL: insert into posts` (title, content, category_id, updated_at, created_at) 值 (T3, kj;k, , 2018-12-20 19:53:52, 2018-12-20 19:53:52))`
  • 您已经使用该名称创建了一个标题T3
  • @Brunaine 是的。我想向用户显示此错误消息。所以我使用 try-catch。
  • 哦,好吧,对不起,我错过了理解,请尝试一下,而不是尝试捕获,只需使用 if( !$post->save() ) { // didn't save } if( $post->save() ) { // did save }

标签: laravel try-catch


【解决方案1】:

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

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

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');

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-21
    • 2020-06-23
    • 1970-01-01
    • 2018-02-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多