Handling exceptions in Laravel 10, especially when it comes to redirecting based on specific exceptions, has some nuances compared to older versions like Laravel 6.x. In Laravel 10, exception handling is primarily managed within the Handler.php file located in app/Exceptions.
Here’s a guide on how to adapt your existing exception handling to work with Laravel 10:
- Update Your Handler.php File You need to modify the register method in the Handler.php file to catch the CertValidationException and handle the redirections.
Open app/Exceptions/Handler.php. Modify the register Method: Add a custom exception handling logic for CertValidationException.
public function register()
{
$this->reportable(function (Throwable $e) {
//
});
$this->renderable(function (CertValidationException $e, $request) {
// Check if it's an AJAX request or a regular request
if ($request->ajax()) {
// Handle AJAX-specific response
return response()->json(['error' => $e->getMessage()], 422);
} else {
// Handle regular web response
Session::put($e->getErrors());
// Logic similar to your catch block
// You may need to adjust this part depending on your application logic
if ($validate || ($mode == 'select' && $cert->phase != 'select')) {
return redirect()->route('certs.sections.edit', [$certId, $sectionId, $mode])
->with('message.error', 'Validation was not successful. Please correct the errors marked below.');
} else {
if (!$internalSubmit) {
if ($request->has('link')) {
return redirect()->to($request->input('link'));
} else {
return redirect()->to('certs');
}
}
}
}
});
}
- Adjust Your Controller Logic In your controller where you previously had the try-catch block, you can now remove the catch part, as the Handler.php will take care of catching and handling the CertValidationException. Make sure any variable used in the catch block ($validate, $certId, $sectionId, $mode, $internalSubmit) is accessible in the Handler.php. You might need to adjust your application logic to ensure these variables are available where needed.