简体   繁体   中英

Is try catch required for simple CRUD operation in Laravel Eloquent

I am less familiar with error handling and my question is different from usually I asked so please guide me if I am wrong. Sample of my CRUD operation:

User::where('active', true)->get(); // index method

User::where('role', 'admin')->first(); // show method

User::create($request->validated()); // store method

$user->update($request->validated()); // update method

$user->delete(); // destroy method

I have a project of Laravel containing following things:

  1. One database (12 - 15 tables)
  2. Model (6 - 8 Models)
  3. CRUD Controller (for each model)
  4. View (index/create/edit for each model)
  5. Middleware ( 5 - 7 user roles)
  6. FormRequest (store/update for each model)
  7. Observer ( for each model to clearing cache items)
  8. Policy ( for each model to check user based role permissions)
  9. Event & Listeners (default/in-built)
  10. Without API & external package installed

Do I need to enclosed try/catch block to each part of my CRUD operation?

try {
    User::where('active', true)->get(); // index method

    User::where('role', 'admin')->first(); // show method

    User::create($request->validated()); // store method

    $user->update($request->validated()); // update method

    $user->delete(); // destroy method

} catch (\Throwable $th) {

    return to_route('home')->with('alert', alert('Error!', "Something went wrong",'error'));

}

Or, if something goes wrong in the DB, Laravel will handle it.

You still have to add a try catch because we can't predict an exception. You certainly don't want when there is an exception the system displays an error page instead of giving notifications to the user.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM