Reputation: 969
Here I have a simple laravel code in post controller that store a post. I want to have unique titles. So I set title in database as unique. In below code I have a try-catch statement. But when I create a post with duplicate title I take error (laravel error page shown ) and catch doesn't call! I don't know why and I confused a little. Can anybody help me please?
$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');
The laravel error page say:
Illuminate \ Database \ QueryException (23000) 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
) values (T3, kj;k, , 2018-12-20 19:53:52, 2018-12-20 19:53:52))
What I want is to show this error to user. So I used try-catch statement. But it seems does't work correctly. In this link seems try-catch should work: Laravel Model->save() returns false but no error . Also I use catch for mange other errors maybe happen
Upvotes: 1
Views: 475
Reputation: 6544
The problem is that you are using Post::create()
outside the try-catch
block. The create()
function will not only create a model instance within memory, but also call save()
on the newly created instance, making your explicit call to save()
redundant.
What you actually want is to use new Post(...)
or Post::create(...)
within the try-catch
block instead:
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');
Upvotes: 4