【问题标题】:Laravel request validation using pivot tableLaravel 使用数据透视表验证请求
【发布时间】:2015-11-13 17:30:50
【问题描述】:

我有一个模特Paper。纸张可以有不同的尺寸和颜色,但尺寸只与某些颜色等有关。我设置了一个数据透视表,其中大小对应于颜色。我正在使用表单请求验证,并且我有为尺寸和颜色设置了 belongsToMany 关系的模型。当我执行Paper:create 时,如果颜色和大小基于该数据透视表不匹配,我想发送一个错误。是否有内置的“Laravel 方式”来实现这一点,或者我应该在设置颜色和大小时循环遍历数据透视表?

【问题讨论】:

标签: php validation laravel-5 pivot-table


【解决方案1】:

我能想到的最“Laravely”的方式是使用这样的表单请求类:

<?php

namespace App\Http\Requests;

use App\Http\Requests\Request;

class PaperFormRequest extends Request
{
    public function authorize()
    {
        return true;
    }

    public function rules()
    {
        // rules here
    }

    protected function getValidatorInstance()
    {
        $validator = parent::getValidatorInstance();

        $validator->after(function() use ($validator) {


            // logic for detecting mismatches goes here


            // To add validation-errors, simply do:
            $validator->errors()->add(
                'colorMistmatch',
                'This color does not go with this paper'
            );

            return $validator;
        }
    }
}

将错误添加到验证器实例后,您可以通过执行以下操作在刀片视图中显示它们:

@if ($errors->has('colorMistmach'))
   {{ $errors->first('colorMistmach') }}
@endif

【讨论】:

    猜你喜欢
    • 2021-10-12
    • 1970-01-01
    • 2016-09-02
    • 2021-02-15
    • 2018-04-10
    • 2016-05-23
    • 2016-03-11
    • 2015-06-09
    相关资源
    最近更新 更多