how to update email admin with Custom Rule?

Viewed 40

I am trying to edit the admin information using a Custom Rule, I want the admin to be able to reset her email when she edits her information but not to reset her email to others.

This is my Custom Rule checkAdminEmailExist.php, please correct it wherever there is a problem

<?php

namespace App\Rules;

use App\Repositories\Interfaces\AdminRepositoryInterface;
use Illuminate\Contracts\Validation\Rule;
use Illuminate\Support\Facades\Auth;

class checkAdminEmailExist implements Rule
{
    public AdminRepositoryInterface $admin_repository;
    public function __construct()
    {
        $this->admin_repository = app()->make(AdminRepositoryInterface::class);
    }
    public function passes($attribute, $value):bool
    {
        if($value == Auth::user()->email) {
            return true;
        }
        if ($this->admin_repository->checkAdminEmailExist($value)) {
            return false;
        }
        return true;
    }
    public function message():string
    {
        return 'The :attribute duplicate';
    }
}
1 Answers

You can leverage try to leverage afterHook like

class UpdateUserRequest extends FormRequest
{    
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array<string, mixed>
     */
    public function rules()
    {
        return [
            /** Other rules **/
            'email' => ['required', 'email'],
        ];
    }
    /**
     * Configure the validator instance.
     *
     * @param  \Illuminate\Validation\Validator  $validator
     * @return void
     */
    public function withValidator($validator)
    {
        $validator->after(function ($validator) {
            $alreadyExists = DB::table('users')
                ->where('id', '<>', auth()->id())
                ->where('email', $this->email)
                ->exists();

            if (auth()->user()->isAdmin() && $alreadyExists) {
                $validator->errors()->add('email', 'The email address is already taken');
            }
        });
    }
}

You will need to implement a isAdmin() method on User model to verify whether the user is an admin or not.

//USer model
public function isAdmin()
{
    //Determine if the user has the role of admin
    return $this->hasRole('admin');

    // or if there's a is_admin boolean column on users table

    return $this->is_admin === true;
}

Laravel Docs - Validation - After Validation Hook

Related