Search code examples
laravellaravel-permission

Catching exceptions when calling role::create and permission::create


I am using laravel permissions and i am creating and destroying permissions a lot and sometimes i cant tell if a user has a certain permission or don't and having to check if a user has a role and permission shall require additional code before i call role::create() for instance.

If i try creating a role that already exists i get a database error and i want for this to fail gracefully like ignore role create or permission create if a user has a specific permission or role i am trying to add.

Does laravel-permissions come with a method to catch such exceptions instead of presenting a user with database errors?.


Solution

  • The simplest way to catch any sql syntax or query errors

    Illuminate\Database\QueryException
    

    try this

    try { 
      role::create()
    } catch(\Illuminate\Database\QueryException $ex){ 
      dd($ex->getMessage()); 
      // Note any method of class PDOException can be called on $ex.
    } catch(Exception $e){
     // order error handeling
    }
    

    see [https://laravel.com/api/6.x/Illuminate/Database/QueryException.html]1