Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

lbabid@gmail.com's avatar

How to make email unique based on user roles (spatie permissions )

Any one has any idea about this,

I have 2 type of users, Admin and Users

When add admin users, the email must be unique , if i add end users ,the email also be unique, Now i want that i have to be able to add admin user with the same email that end user has , I mean email to be unique by role

0 likes
1 reply
MichalOravec's avatar
Level 75

You have to create your own validation rule, where you use joins and check if that email exists in your database.

https://laravel.com/docs/7.x/validation#custom-validation-rules

https://laravel.com/docs/7.x/queries#joins

You can use this joins

use App\User;

Use::select('users.id', 'users.email', 'roles.name as role')
    ->join('model_has_roles', function ($join) {
        $join->on('users.id', '=', 'model_has_roles.model_id')
             ->where('model_has_roles.model_type', User::class);
    })
    ->join('roles', 'model_has_roles.role_id', '=', 'roles.id')
    ->get();

Please or to participate in this conversation.