Laravel 更新数据时在表单请求验证中排除自己,检查指定字段唯一性

原文地址:https://moell.cn/article/24

不错的laravel网站

需求场景
修改用户信息时,在表单请求验证中排除当前邮箱所在的记录行,并检查邮箱的唯一性。

Laravel版本
5.2

路由
backend/user/{user}

实例
<?php
namespace App\Http\Requests\Backend\User;
use App\Http\Requests\Request;
class UpdateRequest extends Request
{
    /**
     * 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
     */
    public function rules()
    {
        $id = $this->route('user'); //获取当前需要排除的id,这里的 user 是 路由 {} 中的参数
        return [
            'email' => "required|email|unique:users,email,".$id,
        ];
    }
}
验证说明
unique:表名,字段,需要排除的ID

  

posted @ 2018-03-15 16:39  生如逆旅,一苇以航  阅读(863)  评论(0编辑  收藏  举报