Pranav Mandlik
Pranav Mandlik

Reputation: 644

Handle exception in laravel

I have written code for creating roles in laravel i am using spatie package when i try to create new role then it gives exception like Spatie \ Permission \ Exceptions \ RoleDoesNotExist

I know its generating because role does not exists, i dont know how to handle exception in laravel.

also is there any way i can first check role exists or not and then add the role? following is my code

public function create()
    {
         //print_r($_POST);
         $role_name=$_POST['name'];
         $create_product=NULL;
         $edit_product=NULL;
         $view_product=NULL;

          if(isset($_POST['create_products']))
         {
            $create_product=$_POST['create_products'];
         }
         if(isset($_POST['view_products']))
         {
            $view_product=$_POST['view_products'];
         }
          if(isset($_POST['edit_products']))
         {
            $edit_product=$_POST['edit_products'];
         }
         echo $create_product; echo $view_product; echo $edit_product;

         dd(Role::findByName($role_name));

Upvotes: 0

Views: 344

Answers (4)

siddhant sankhe
siddhant sankhe

Reputation: 633

Try using laravel`s findOrNew. It will attempt to locate a record in the database matching the given attributes. However, if a model is not found, a new model instance will be returned.

$role = Role::firstOrNew(array('name' => Input::get('role_name'))); 
$role->name = Input::get('role_name'); 
$role->save();

Upvotes: 1

user320487
user320487

Reputation:

You can check if a model exists by calling the exists method:

if (Model::where('attribute', $value)->exists()) {
    // do something 
}

Upvotes: 0

Turan Zamanlı
Turan Zamanlı

Reputation: 3926

you should load class with namespace in the current file.

f.e

Use App\Lib\Role;

Upvotes: 0

Pranav Mandlik
Pranav Mandlik

Reputation: 644

i have checked given role exists in database like

 $s=Role::where('name', $role_name)->count();


         if($s==1)
        {
            echo "Role Already Exists";
        }
        else{

        }

Thanks for your help

Upvotes: 0

Related Questions