Optimal way to capture error while creating record in Laravel
I have below code which insert record in job_titles
table which is working perfectly fine. I have used double check in that code in case of failures(Try/Catch and If Statement). I needed to know is it really required or only one method can suffice. If only one method is sufficient then which one i should use.
public function store(Request $request)
{
try {
$rules = [
'code' => 'required | max:4 | unique:job_titles,code',
'title' => 'required',
'description' => 'required'
];
$validated = Validator::make($request->all(), $rules);
if ($validated->fails()) {
return response()->json(['status' => 'error', 'message' => 'Please correct validation errors', 'errors' => $validated->errors()]);
}
$newJobTitle = JobTitle::create([
'title' => $request->get('title'),
'code' => strtoupper($request->get('code')),
'description' => $request->get('description')
]);
if (!$newJobTitle) {
return response()->json(['status' => 'error', 'message' => 'Something went wrong!!']);
}
return response()->json([
'status' => 'success',
'message' => 'Job Title ' . $request->get('title') . ' created successfully'
]);
} catch (Exception $e) {
return response()->json(['status' => 'error', 'message' => 'Something went wrong!!', 'exception_message' => $e]);
}
}
I have confusion Between these:
try{
}catch(Exception e)
{
}
OR
$newJobTitle = JobTitle::create([
'title' => $request->get('title'),
'code' => strtoupper($request->get('code')),
'description' => $request->get('description')
]);
if (!$newJobTitle) {
return response()->json(['status' => 'error', 'message' => 'Something went wrong!!']);
}
OR
Both the above option
from Laravel Questions and Answers https://laravelquestions.com/laravel/optimal-way-to-capture-error-while-creating-record-in-laravel/
via Lzo Media
No comments:
Post a Comment