Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

julianov's avatar

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);
    }

}
0 likes
2 replies
Tray2's avatar

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.

1 like
pemudakoding's avatar

On my perspective I'm only use try and catch when I want to catch some exception and give accurate response that relate with the exception, if you didn't want catch any exception and you can go thru without try and catch.

unless you need change the response structure of error that came from base on Laravel. you can do that for catch \Throwable (Unknown exception)

1 like

Please or to participate in this conversation.