I almost never use try catch so it isn't strictly necessary. The only time I use them is when I expect something to go wrong.
Nov 4, 2022
2
Level 1
try and catch clause in laravel controller methods.
Hello everyone. I would like to know if it is necessary to add the try and catch tags in each method of the controller.
I generally use the following line to validate the request data:
if (Auth::attempt($validated))
But in this case there is no user yet to validate because it is the singup function
public function singup(Request $request)
{
try {
$validated = $this->validate($request, [
'name' => 'required',
'last_name' => 'required',
'email' => 'required',
'password' => 'required',
]);
$user = new User();
$user->name= $validated['name'];
$user->last_name= $validated['last_name'];
$user->email = $validated['email'];
$user->password = bcrypt($validated['password']);
$user->save();
$code = random_int(1000,9999);
Mail::to('[email protected]')
->cc('[email protected]')
->queue((new EmailConfirmation($user , $code))->from('[email protected]', 'Laravel'));
return response()->json([
'status' => true,
'message' => 'Email sent',
], 201);
} catch (\Throwable $th) {
return response()->json([
'status' => false,
'message' => $th->getMessage()
], 500);
}
}
Please or to participate in this conversation.