Laravel:如何根据Model's属性的可能值验证表单字段


Laravel : how to validate a form field according to possible values of a Model's attribute?

我正在执行表单验证,其中用户可以选择一个值范围(基于模型中的一组条目)

。我有模型CfgLocale(id, name)

我想要这样的东西:

CfgLocale->listofAvailableIds():返回一个数组

我所做的是:

Inside Model this method:

class CfgLocale extends Model
{
    protected $table = 'cfg_locales';

    public static function availableid()
    {
        $id_list = [];
        $res = self::select('id')->get();
        foreach($res as $i){
            $id_list[] = $i->id;
        }
        return $id_list;
    }
}

在控制器上进行验证,我会这样做:

$this->validate($request, [
    'id'                => 'required|integer|min:1',
    ...
    'locale'  => 'required|in:'.implode(',', CfgLocale::availableid()),
]);

有更好的想法,或Laravel标准来完成这个?

谢谢

您可以使用laravel的exists规则。您可以定义验证规则,如下所示。也许这能帮上忙。

'locale' => 'exists:cfg_locales,id'

请使用以下代码,

class CfgLocale extends Model
{
    protected $table = 'cfg_locales';
    public static function availableid()
    {
        return $this->pluck('id')->toArray();
    }
}

pluck方法从表中选择id列,toArray方法将模型object collection转换为array

点击这里了解更多关于Laravel Collections的信息

这将返回一个id数组:

public static function availableid()
{
    return $this->pluck('id')->toArray();
}

https://laravel.com/docs/5.3/collections method-pluckhttps://laravel.com/docs/5.3/collections method-toarray