我制定了一个自定义验证规则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条记录时,此方法有效。 issue是当表为空时,即使表中还没有记录,也返回验证错误消息,因此没有最大值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();
表为空时,相同的问题仍然存在。有谁知道这里可能是什么问题?欢迎任何帮助或建议
<?php
declare(strict_types=1);
namespace App\Rules;
use Illuminate\Contracts\Validation\Rule;
use App\EtudiantsChoixTheme;
class FiveMaxThemesChoice implements Rule
{
private const MAXIMUM_NUMBER_OF_THEMES = 5;
public function passes($attribute, $value): bool
{
$etudiants = EtudiantsChoixTheme::where('idEtudiant', auth()->user()->id);
return $etudiants->count() <= self::MAXIMUM_NUMBER_OF_THEMES;
}
public function message(): string
{
return 'You have already chosen a maximum of 5 themes.';
}
}