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
dd($request->all());
to see what comes in the request to see if it is all correct. And what does the laravel error page says? – Brunaine Dec 20 '18 at 20:09SQLSTATE[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))` – Karim Pazoki Dec 20 '18 at 20:10T3
– Brunaine Dec 20 '18 at 20:11if( !$post->save() ) { // didn't save }
andif( $post->save() ) { // did save }
– Brunaine Dec 20 '18 at 20:14