首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何用自定义规则更新电子邮件管理?

如何用自定义规则更新电子邮件管理?
EN

Stack Overflow用户
提问于 2022-06-05 04:29:56
回答 1查看 46关注 0票数 2

我试图编辑管理信息使用自定义规则,我希望管理员能够重置她的电子邮件时,她编辑她的信息,但不重置她的电子邮件给其他人。

这是我的自定义规则checkAdminEmailExist.php,请在有问题的地方纠正它

代码语言:javascript
复制
<?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';
    }
}
EN

回答 1

Stack Overflow用户

发布于 2022-06-05 05:31:21

您可以尝试利用afterHook,如

代码语言:javascript
复制
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');
            }
        });
    }
}

您需要在用户模型上实现一个isAdmin()方法,以验证用户是否是管理员。

代码语言:javascript
复制
//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文档-验证-验证后挂钩

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/72504801

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档