How to customize user validation rule with multiple access levels?

Asked

Viewed 120 times

-1

I need to do a validation in the user registration where an email can only be validated if in the table users your level of access is not company level. On the table users, there is already a field called nivel which classifies this type of level of users.

Remembering that my application is written in Laravel 5.6.

So far I have this validation:

$validate = $request->validate([
    'name' => 'required|min:3',
    'email' => 'required|email|unique:users',
    'phone' => 'required'
]);

I believe that for this situation I need to make a more personalized rule yet I do not have the necessary knowledge.

From now on I thank you for your help.

  • I point out you study ACL that it becomes much easier to understand this, but if you want to use these indico ways to understand the Gates with it you will define who can see or can not see.

2 answers

0

Example using your code as level, you go into providers and Authserviceproviders and boot puts:

public function boot(){

   Gate::define('Admin', function(User $user){
     return $user->nivel === "Admin"; //Valida se é Admin ou oque for criar
   } );
}

In the controller you will use as follows:

public function index(){

     if(Gate::allows('Admin')){
         return true; //Caso tenha permissão Admin
     }

     return false; //Caso não tenha permissão Admin

}

NOTE: Don’t forget to use Gate in the controller and Authserviceprovider and also don’t forget to use App User to catch the logged in user.

I hope I’ve helped you any doubt just comment!.

Reference: https://laravel.com/docs/5.8/authorization#Gates

0

I was able to find a solution... The idea I had was this:

  1. Create a FormRequest
  2. Define validation rules for each form field.
  3. Create a Rule specific to validate the e-mail.
  4. Call this Rule in the validation rules of FormRequest.

Code

Controller

public function storeUsuarioEmpresa(UsuarioEmpresaRequest $request)
{
    ...
}

app/Requests/Usuarioempresarequest.php

public function rules()
{
    $rules = [
        'name' => 'required|min:3',
        'phone' => 'required',
    ];

    $rules['email'] = ['required', 'email', 'max:100', new UsuarioEmpresaRule($this->email)];

    return $rules;
}

app/Rules/Usuarioempresarule.php

public function passes($attribute, $value)
{
    $user = Usuarios::getByEmail($this->email);
    if (empty($user)) {
        return true;
    }
    return $user->nivel != 2;
}

public function message()
{
    return 'Este e-mail já está cadastrado!';
}

That way I managed to reach my goal.

Comment on what you think or suggest improvement.

Thanks!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.