首页 > 解决方案 > 将查询结果计数用于验证规则(即使为空)

问题描述

我已经制定了一个自定义验证规则fiveMaxThemesChoice,其名称可以解释为在我正在构建的应用程序中将用户 ( Etudiant) 限制为最多 5 个选择。themes这是EtudiantsChoixTheme我在 Eloquent 中注册选择的逻辑:

<?php

namespace App\Rules;

use Illuminate\Contracts\Validation\Rule;
use App\EtudiantsChoixTheme;

class fiveMaxThemesChoice implements Rule
{
    /**
     * Create a new rule instance.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * Determine if the validation rule passes.
     *
     * @param  string  $attribute
     * @param  mixed  $value
     * @return bool
     */
    public function passes($attribute, $value)
    {
        $choixEtudiants = EtudiantsChoixTheme::all();

            foreach ($choixEtudiants as $choixEtudiant) {
                  $IdEtudiantOccurences = count($choixEtudiants->where('idEtudiant', auth()->user()->id));
                if($IdEtudiantOccurences <= 5){
                    return true;
                }
                else{
                    return false;
                }
            }
    }

    /**
     * Get the validation error message.
     *
     * @return string
     */
    public function message()
    {
        return 'You have already chosen a maximum of 5 themes.';
    }
}

当表中至少有 1 条记录时,此方法有效。问题是当表变空时,即使表中还没有任何记录,也会返回验证错误消息,因此不是最大值 5(所以<= 5应该是正确的)。为什么这不起作用?

我尝试过不同的语法:

$IdEtudiantOccurences = count($choixEtudiants->where('idEtudiant', auth()->user()->id)->first());
$IdEtudiantOccurences = $choixEtudiants->where('idEtudiant', auth()->user()->id)->first()->count();
$IdEtudiantOccurences = $choixEtudiants->where('idEtudiant', auth()->user()->id)->count();

当表为空时,同样的问题仍然存在。有谁知道这里可能是什么问题?欢迎任何帮助或建议

标签: phplaravelvalidationcountrules

解决方案


<?php
declare(strict_types=1);

namespace App\Rules;

use Illuminate\Contracts\Validation\Rule;
use App\EtudiantsChoixTheme;

final class FiveMaxThemesChoice implements Rule
{
    private const MAXIMUM_NUMBER_OF_THEMES = 5;

    public function passes($attribute, $value): bool
    {
        $idEtudiant = auth()->user()->id;
        $etudiantsQuery = EtudiantsChoixTheme::where('idEtudiant', $idEtudiant);

        return $etudiantsQuery->count() <= self::MAXIMUM_NUMBER_OF_THEMES;
    }

    public function message(): string
    {
        return 'You have already chosen a maximum of 5 themes.';
    }
}

而不是获取所有(EtudiantsChoixTheme::all();)尝试直接进行查询并在它之后询问总数(EtudiantsChoixTheme::where(...)->count()

我从官方文档中获得了这个想法:https ://laravel.com/docs/4.2/queries


推荐阅读