Laravel添加验证场景提高针对性质的验证

laravel没有场景验证的概念,是一个验证类验证一个函数,验证数据不是很方便,封装补足一下

封装添加场景的方法

<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Support\Str;
use Illuminate\Http\Exceptions\HttpResponseException;
use Illuminate\Contracts\Validation\Validator;

/**
 * 使用方法:
 * Class AbstractRequest
 * @package App\Http\Requests
 */
class BaseRequest extends FormRequest
{
    public $scenes = [];
    public $currentScene;               //当前场景
    public $autoValidate = false;       //是否注入之后自动验证

    public function authorize()
    {
        return true;
    }

    /**
     * 设置场景
     * @param $scene
     * @return $this
     */
    public function scene($scene)
    {
        $this->currentScene = $scene;
        return $this;
    }



    /**
     * 覆盖自动验证方法
     */
    public function validateResolved()
    {
        if ($this->autoValidate) {
            $this->handleValidate();
        }
    }

    /**
     * 验证方法
     * @param string $scene
     * @throws \Illuminate\Auth\Access\AuthorizationException
     * @throws \Illuminate\Validation\ValidationException
     */
    public function validate($scene = '')
    {
        if ($scene) {
            $this->currentScene = $scene;
        }
        $this->handleValidate();
    }

    /**
     * 根据场景获取规则
     * @return array|mixed
     */
    public function getRules()
    {
        $rules = $this->container->call([$this, 'rules']);
        $newRules = [];
        if ($this->currentScene && isset($this->scenes[$this->currentScene])) {
            $sceneFields = is_array($this->scenes[$this->currentScene])
                ? $this->scenes[$this->currentScene] : explode(',', $this->scenes[$this->currentScene]);
            foreach ($sceneFields as $field) {
                if (array_key_exists($field, $rules)) {
                    $newRules[$field] = $rules[$field];
                }
            }
            return $newRules;
        }
        return $rules;
    }

    /**
     * 覆盖设置 自定义验证器
     * @param $factory
     * @return mixed
     */
    public function validator($factory)
    {
        return $factory->make(
            $this->validationData(), $this->getRules(),
            $this->messages(), $this->attributes()
        );
    }

    /**
     * 最终验证方法
     * @throws \Illuminate\Auth\Access\AuthorizationException
     * @throws \Illuminate\Validation\ValidationException
     */
    protected function handleValidate()
    {
        $instance = $this->getValidatorInstance();
        if ($instance->fails()) {
            $this->failedValidation($instance);
        }
        $this->passedValidation();
    }
    /**
     * 重写报错部分-适应API JSON下发的需求
     */
    protected function failedValidation(Validator $validator)
    {
        $error= $validator->errors()->all();
        throw new HttpResponseException(response()->json(['code'=>505,'msg'=>$error['0'],'data'=>[]]));
    }

}

验证类的使用

<?php

namespace App\Http\Requests;


class MsgBoardRequest extends BaseRequest
{



    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            'id'=>'required',
            'title' => 'required|max:10',
            'content' => 'required|max:255',
        ];
    }
    /**
     * 获取已定义验证规则的错误消息
     *
     * @return array
     */
    public function messages()
    {
        return [
            'id.required'=>'ID不能为空',
            'title.max' =>'标题太长了,简化一下吧',
            'title.required'  => '标题不能为空',
            'content.max' => '内容太多了',
            'content.required'  => '内容不能为空',
        ];
    }
    public $scenes = [
        'addMsg' => ['title', 'content'],
        'deleteMsg' =>['id']
    ];
}

控制器中进行调用

public function addMsg(MsgBoardRequest $request){
	$request->validate('addMsg');
}
public function deleteMsg(MsgBoardRequest $request){
    $request->validate('deleteMsg');
}

 

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
要在 Laravel-admin 的登录界面添加验证码,可以参考以下步骤: 1. 安装验证码库 可以使用 Laravel 自带的验证码库,也可以使用其他第三方库,这里以 Laravel 自带的验证码库为例。在 Laravel 中,可以使用 Composer 安装验证码库: ``` composer require mews/captcha ``` 2. 生成验证码 在登录页面的表单中添加验证码输入框和验证码图片,然后在后台生成验证码并将其显示在表单中。可以在登录页面的控制器中添加以下代码: ``` use Mews\Captcha\Captcha; public function getLogin() { $captcha = new Captcha(); $captcha->setFontSize(18); $captcha->setLength(4); $captcha->setBackgroundColor(255,255,255); $captcha->setFontColor(0, 0, 0); $captcha->generate(); $captcha_image = $captcha->inline(); return view('admin.login', compact('captcha_image')); } ``` 这段代码生成了一个验证码,并将其嵌入到 HTML 中,然后将其传递给登录页面的视图。 3. 验证验证码 在用户提交表单时,需要验证用户输入的验证码是否正确。可以在登录页面的控制器中添加以下代码: ``` use Illuminate\Support\Facades\Validator; use Illuminate\Validation\Rule; use Mews\Captcha\Captcha; public function postLogin(Request $request) { $validator = Validator::make($request->all(), [ 'username' => 'required', 'password' => 'required', 'captcha' => [ 'required', Rule::exists('captcha')->where(function ($query) use($request) { $query->where('captcha', $request->captcha)->where('captcha_type', 'admin_login'); }) ], ], [ 'captcha.exists' => '验证码不正确', ]); if ($validator->fails()) { return redirect()->back()->withErrors($validator)->withInput(); } // 验证通过,进行登录操作 // ... } ``` 这段代码使用 Laravel 自带的表单验证功能,验证用户输入的验证码是否正确。如果验证码不正确,会返回错误信息。如果验证码正确,则进行登录操作。 4. 添加验证码表 为了保存验证码信息,需要在数据库中添加一个验证码表。可以使用以下 SQL 语句创建一个验证码表: ``` CREATE TABLE `captcha` ( `id` int(10) unsigned NOT NULL AUTO_INCREMENT, `captcha` varchar(10) NOT NULL, `captcha_type` varchar(50) NOT NULL, `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; ``` 这个表只包含三个字段:`id`、`captcha` 和 `captcha_type`。`id` 是自增主键,`captcha` 是验证码的内容,`captcha_type` 是验证码的类型,用于区分不同场景下的验证码。 5. 保存验证码信息 在生成验证码时,将验证码信息保存到数据库中。可以在 `getLogin` 方法中添加以下代码: ``` use Mews\Captcha\Captcha; use App\Models\Captcha as CaptchaModel; public function getLogin() { $captcha = new Captcha(); $captcha->setFontSize(18); $captcha->setLength(4); $captcha->setBackgroundColor(255,255,255); $captcha->setFontColor(0, 0, 0); $captcha->generate(); $captcha_image = $captcha->inline(); $captcha_db = new CaptchaModel(); $captcha_db->captcha = $captcha->getPhrase(); $captcha_db->captcha_type = 'admin_login'; $captcha_db->save(); return view('admin.login', compact('captcha_image')); } ``` 这段代码使用 `Captcha` 类生成验证码,并将验证码内容和类型保存到数据库中。 6. 清理过期验证码 为了避免数据库中出现大量过期的验证码,可以定期清理过期的验证码。可以在 `Kernel` 类中添加一个定时任务,每天清理过期的验证码: ``` use App\Models\Captcha; use Carbon\Carbon; protected function schedule(Schedule $schedule) { $schedule->call(function () { $expired_at = Carbon::now()->subMinute(30); Captcha::where('created_at', '<', $expired_at)->delete(); })->daily(); } ``` 这段代码每天执行一次,删除创建时间早于 30 分钟前的验证码记录。 以上就是向 Laravel-admin 登录界面添加验证码的步骤。
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值