1

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?.

Gandalf
  • 1
  • 29
  • 94
  • 165
  • please mention what `laravel-permissions` package you are using or it's custom .? – Kamlesh Paul Feb 07 '20 at 12:20
  • Its in the tag. Its laravel permission https://docs.spatie.be/laravel-permission/v3/basic-usage/basic-usage/ – Gandalf Feb 07 '20 at 12:25
  • i think for `role:create()` package have helpers you can use that – Kamlesh Paul Feb 07 '20 at 12:27
  • I don't think there is. There is only one exception handler `Spatie\Permission\Exceptions\RoleAlreadyExists` for that.I havent seen any helper though. – Gandalf Feb 07 '20 at 12:37
  • I shall just have to seed the roles and permissions as `$user->assignRole("writer");` for instance handles any duplicate without throwing database errors and that is good enough for me. – Gandalf Feb 07 '20 at 19:43

1 Answers1

0

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

Mohammad
  • 652
  • 1
  • 7
  • 18