koalaok koalaok - 2 years ago 91
PHP Question

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

I'm performing validation of a form, where a user may select a range of values (based on a set of entries in a model)

E.g. I have the Model CfgLocale(id, name)

I would like to have something like:

CfgLocale->listofAvailableIds() : return a array

What I did is:

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;

On Controller for validation I would do then:

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

Any better Idea, or Laravel standard to have this done?


Answer Source

You can use exists rule of laravel.You can define a validation rule as below. Might be this can help.

'locale' => 'exists:cfg_locales,id'
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download