laravel

laravel5.8验证规则【附laravel5.8视频教程】

2019-08-06  本文已影响1人  这真的是一个帅气的名字

创建验证文件

php artisan make:request StoreCate

验证规则

<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

class StoreCate 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
     */
    public function rules()
    {
        return [
            'cname' => 'required|max:50',
            'sort' => 'required|integer'
        ];
    }

    /**
     * 获取验证错误的自定义属性。
     *
     * @return array
     */
    public function attributes()
    {
        return [
            'cname' => '分类名称',
            'sort' => '排序'
        ];
    }

    /**
     * 获取已定义验证规则的错误消息。
     *
     * @return array
     */
    public function messages()
    {
        return [
            'cname.required' => '分类名称不能为空',
            'cname.max:50'  => '分类名称不能超过50个字符',
            'sort.integer' => '排序必须是数字',
            'sort.required' => '排序不能为空',

        ];
    }
}

添加方法使用验证

//StoreCate必须经过use才行   use App\Http\Requests\StoreCate;

    public function store(StoreCate $request)
    {
        $category = new Cate();
        $category->name = $request->cname;
        $category->sort = $request->sort;
        $category->pid = $request->pid;
        $res = $category->save();
        if($res){
            $request->session()->flash("success","添加成功");
        }else{
            $request->session()->flash("errormsg","用户名或密码错误");
        }
        return redirect('admin/cate/index');
    }

模板

@if ($errors->any())
    @foreach ($errors->all() as $error)
    <div class="alert alert-danger">
        {{ $error }}
    </div>
    @endforeach
@endif




本人有份laravel5.8教学课程,需要的同学可以关注公众号:小贝壳的资源库恢复laravel获取


小贝壳的资源库
上一篇下一篇

猜你喜欢

热点阅读