Reputation: 644
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
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
Reputation:
You can check if a model exists by calling the exists
method:
if (Model::where('attribute', $value)->exists()) {
// do something
}
Upvotes: 0
Reputation: 3926
you should load class with namespace in the current file.
f.e
Use App\Lib\Role;
Upvotes: 0
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