rescue helper in Laravel, Provides technique to handle exception , Where you can pass parameters as in closure methods.
When this rescue helper executes the closure and catch any exception during execution , It caught all exception and thrown all exception a into exception handler.
We are giving example to caught all exception and thrown all exception into exception handler using rescue helper.
public function store(Request $request) { rescue(function () { $user = new User(); $user->name = $request['name']; $user->user_id = Auth::user()->id; $user->c_id = $request['courseId']; $user->save(); }, function() { request()->session()->flash('unsuccessmsg', 'Failed to add user records.'); return redirect()->back(); }, true); }
Based on above example, rescue() helper can accept three arguments.
1st Parameters – It having code that we want exception handled.
2nd Parameters – This is optional closure , exception area occurred when executed this block of code or return the default value when exception are found .
3rd parameters– It is optional parameters accepts boolean that determine whether report the exception return or not.
- If its true, rescue helper return the exception
- If its false, rescue helper don’t return any exception.
If you want to know that how to define rescue helper i original . Please look at the below code
** * Catch a potential exception and return a default value. * * @param callable $callback * @param mixed $rescue * @param bool $report * @return mixed */ function rescue(callable $callback, $rescue = null, $report = true) { try { return $callback(); } catch (Throwable $e) { if ($report) { report($e); } return $rescue instanceof Closure ? $rescue($e) : $rescue; } }
I hope , It makes you to clear idea about rescue() helper that helps in your coding .