jeudi 8 février 2018

Laravel : Dynamic field validation

I have forms that are dynamically generated and I would like to apply a specific validation rule foreach different type of field available.

I can have this kind of forms dynamically created:

  • 2 inputs and 1 textarea
  • 1 checkbox and 2 selects
  • 1 input and 2 checkboxes
  • ...

And I have this code

public function storeDynamic(Request $request)
{

    foreach ($request->except('_token') as $field_id => $value) 
    {
        $type = \App\Field::find( $field_id )->type;

        switch ( $type ) 
        {
            case 'input':
                //required
                break;

            case 'select':
                //required|max:255
                break;

             ...

        }
    }

    //Store in DB
    //Flash confirmation message
    //Redirect
}

Usually I use this kind of code for validation

$this->validate($request, [  
    'title' => 'required|max:145',
    'description' => 'max:255'
]);

I'm sure laravel has a magic way to do this but I can't find anything in the documentation.

So is it possible to validate the field one by one through my loop?



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire