我的laravel try-catch语句不';行不通
在这里,我有一个简单的laravel代码在post控制器中存储一篇文章。我想拥有独一无二的头衔。所以我将数据库中的标题设置为唯一。在下面的代码中,我有一个try-catch语句。但当我创建一篇标题重复的文章时,我会出错(laravel错误页面显示)),catch不会调用!我不知道为什么,我有点困惑。有人能帮我吗我的laravel try-catch语句不';行不通,laravel,try-catch,Laravel,Try Catch,在这里,我有一个简单的laravel代码在post控制器中存储一篇文章。我想拥有独一无二的头衔。所以我将数据库中的标题设置为唯一。在下面的代码中,我有一个try-catch语句。但当我创建一篇标题重复的文章时,我会出错(laravel错误页面显示)),catch不会调用!我不知道为什么,我有点困惑。有人能帮我吗 $post = Post::create([ 'title' => $request->title, 'content' =>
$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错误页面显示:
Illumb\Database\QueryException(23000)SQLSTATE[23000]:
完整性约束冲突:密钥的1062个重复条目“T3”
“posts\u title\u unique”(SQL:插入到posts
(title
,content
),
类别id
,在
处更新,在
处创建)值(T3,kj;k,
2018-12-20 19:53:522018-12-20 19:53:52)
我想要的是向用户显示此错误。所以我使用了try-catch语句。但它似乎不能正常工作。
在此链接中,try-catch应该可以工作:。此外,我还使用catch来管理可能发生的其他错误问题是您在
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');
问题在于,您正在
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');
尝试使用
dd($request->all())
查看请求中的内容,查看是否都正确。laravel错误页面是怎么说的?@Brunaine laravel错误页面说:SQLSTATE[23000]:完整性约束冲突:1062个重复条目“T3”用于键“posts\u title\u unique”(SQL:insert-into
posts)(title
,content
,category\u id
,在
处更新,在
处创建)值(T3,kj;k,2018-12-20 19:53:522018-12-20 19:53:52)`您已经创建了一个名为T3
@Brunaine的标题。我想向用户显示此错误消息。因此我使用了try-catch。哦,很抱歉,我没有理解,请尝试一下,如果(!$post->save()){//not save},请使用if(!$post->save()){//not save}
和if($post->save()){//did save}
尝试使用dd($request->all());
查看请求中的内容是否正确。laravel错误页面会说什么?@Brunaine laravel错误页面会说:SQLSTATE[23000]:完整性约束冲突:1062个重复条目“T3”用于关键字“posts\u title\u unique”(SQL:插入到
posts`(title
,content
,category\u id
,在
处更新,在
处创建)值(T3,kj;k,2018-12-20 19:53:522018-12-20 19:53:52))`您已经创建了一个名为T3
@Brunaine的标题。是的。我想向用户显示此错误消息。因此我使用了try-catch。哦,好的,很抱歉我没有理解,请尝试一下,而不是使用try-catch,只要使用if(!$post->save()){//not save}
和if($post->save()){//did save}