【问题标题】:custom validation about unique of more than one field in laravel关于 laravel 中多个字段的唯一性的自定义验证
【发布时间】:2017-08-14 11:14:05
【问题描述】:

我有一张桌子tanks

+----+----------+-------+-------+
| id | capacity | model | width |
+----+----------+-------+-------+
|  1 |     1000 |    15 |   960 |
|  2 |    50000 |    30 |   200 |
|  3 |      100 |    15 |    12 |
|  4 |    80000 |    40 |   100 |
|  5 |     1000 |    30 |   123 |
|  6 |      500 |     5 |  1213 |
|  7 |     1000 |    22 |  2234 |
+----+----------+-------+-------+

我在表中添加了唯一属性

ALTER TABLE `tanks`
ADD UNIQUE `capacity_model_width` (`capacity`, `model`, `width`);

而我存储值的功能是这样的

public function store(Request $request) {

        $image = new tank();

        $this->validate($request, [
                'capacity' => 'required|numeric',
                'model' => 'required|numeric',
                'width' => 'required|numeric',
            ]                
                );

        $image->capacity = $request->capacity;
        $image->model = $request->model;
        $image->width = $request->width;
        $image->save();

        return redirect()->route('tank.index')
                        ->with('success', 'Tank created successfully');
    }

现在当我在下面插入错误显示时

Integrity constraint violation: 1062 Duplicate entry 
'1000-22-2234' for key 'capacity_model_width'

如果它们是唯一的,我需要在我的提交中显示错误消息。我是 Laravel 新手,如何在 store 函数中添加自定义验证和错误消息

【问题讨论】:

  • 那么你是在连接模型宽度和钥匙的容量吗?
  • 有一个验证规则unique
  • @ChrisTownsend no concatenation for them
  • @AhmadRezk 我知道,但它不适用于两个或多个领域,它对我不起作用
  • 那么你的钥匙是怎么变成'1000-22-2234'的?

标签: php mysql laravel unique


【解决方案1】:

验证中的简单更改

this->validate($request, [
                'capacity' => 'required|email|unique:table_name',
                'model' => 'required|email|unique:table_name',
                'width' => 'required|email|unique:table_name',
            ]

【讨论】:

  • 每一个我需要三个字段
【解决方案2】:

将唯一的验证规则添加到这样的容量中

$this->validate($request, [
            'capacity' => 'required|numeric|unique:tanks,capacity',
            'model' => 'required|numeric',
            'width' => 'required|numeric',
        ]                
            );

你可以添加额外的 Where 子句

 Validator::make($request, [
'capacity' => Rule::unique('tanks')->where(function ($query) use $request {
$query->where('capacity', $request->input('capacity'))->where('width', $request->input('width'))->where('model', $request->input('model'));
})
]); 

laravel unique doc

【讨论】:

  • 它的容量只有我需要三个字段一起
【解决方案3】:

将此添加到您的代码中

我们将首先检查我们需要的字段是否存在,然后我们将连接它们并将它们添加到请求中。从那里我们现在可以运行我们独特的验证

public function store(Request $request) {
    $image = new tank();
    //Check to see if fields exist then validate after concatenation

    if(isset($request->capacity) && isset($request->model) && isset($request->width) ){
         $request->request->add(['my_key' => ['capacity' => $request->capacity, 'model' => $request->model, 'width' => $request->width] ]);
    }
    $this->validate($request, [
            'capacity' => 'required|numeric',
            'model' => 'required|numeric',
            'width' => 'required|numeric',
            'my_key' => 'required|uniqueCapacity',
        ]                
            );

    $image->capacity = $request->capacity;
    $image->model = $request->model;
    $image->width = $request->width;
    $image->save();

    return redirect()->route('tank.index')
                    ->with('success', 'Tank created successfully');
}

添加自定义验证器

首先访问您的 AppServiceProvider 并添加以下内容

class AppServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        Validator::extend('uniqueCapacity', function ($attribute, $value, $parameters, $validator) {
       $value_array = explode("-", $value);
        $items = DB::select("SELECT count(*) as aggregate FROM tanks WHERE capacity ='$value_array[0]' AND model='$value_array[1]' AND width='$value_array[2]' "); 
        $number=$items[0]->aggregate;
        if ($number > 0) {
            return false;
        } else {
            return true;
        }
        });
    }

    /**
     * Register the service provider.
     *
     * @return void
     */
    public function register()
    {
        //
    }
}

【讨论】:

  • 另一个选项是您可以在隐藏字段中自动连接 JavaScript 中的字段。然后可以通过请求传递
  • 未找到列:1054 'where 子句'中的未知列'capacity_model_width'(SQL:从tanks 中选择计数(*)作为聚合,其中capacity_model_width = 1000-22-2234)跨度>
  • 好的,表中实际上不存在该列?这只是一个规则?
  • 感谢它在我自己的一点点修改中工作
  • 你能这样改答案吗
猜你喜欢
  • 2018-04-28
  • 2021-11-30
  • 2023-03-20
  • 2014-12-16
  • 2018-05-11
  • 2019-12-10
  • 2016-09-26
  • 2020-10-24
相关资源
最近更新 更多