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

  

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在Yii2,可以使用ActiveForm widget来创建表单,并在验证失败自动高亮显示错误字段。要在表单高亮显示验证失败的字段,可以按照以下步骤操作: 1. 在视图使用ActiveForm widget创建表单: ```php <?php use yii\widgets\ActiveForm; ?> <?php $form = ActiveForm::begin(); ?> <!-- 表单字段 --> <?php ActiveForm::end(); ?> ``` 2. 在控制器处理表单提交并进行验证: ```php public function actionCreate() { $model = new MyModel(); if ($model->load(Yii::$app->request->post()) && $model->validate()) { // 保存数据 return $this->redirect(['view', 'id' => $model->id]); } else { return $this->render('create', [ 'model' => $model, ]); } } ``` 3. 在视图使用ActiveField widget来定义每个表单字段,并将其与模型属性绑定: ```php <?php use yii\widgets\ActiveForm; ?> <?php $form = ActiveForm::begin(); ?> <?= $form->field($model, 'name')->textInput() ?> <?= $form->field($model, 'email')->textInput() ?> <!-- 其他表单字段 --> <?php ActiveForm::end(); ?> ``` 4. 在视图使用$form->errorSummary()方法来显示所有验证错误消息: ```php <?php use yii\widgets\ActiveForm; ?> <?php $form = ActiveForm::begin(); ?> <?= $form->field($model, 'name')->textInput() ?> <?= $form->field($model, 'email')->textInput() ?> <!-- 其他表单字段 --> <?= $form->errorSummary($model); ?> <?php ActiveForm::end(); ?> ``` 此,在表单输入不合法的数据并提交后,所有验证失败的字段会自动高亮显示,并显示相应的错误消息。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值