5

Is it possible to create a dynamic FormRequest validation in my function? See sample code below.

public function store(Request $request)
{
    Model::create($request->all());
    return redirect(url('/'));
}

What I mean is that I will change the "Request" parameter to the variable $formRequest.

My goal is that I would like to create different validation rules for a dynamic set of data of a single model.

If I could achieve this with other ways, please let me know. Thank you!

Edit:

Sample scenario: I have a form that has fields of First Name, Middle Name and Last Name.

First Rule:

public function rules()
{
    return [
    'firstname' => 'required',
    'middlename' => 'required',
    'lastname' => 'required'
    ];
}

Second Rule:

public function rules()
{
    return [
    'firstname' => 'required',
    'lastname' => 'required'
    ];
}

Where in the second rule only requires first and last name.

I just want to know if there are other ways of doing this rather than creating multiple store methods and adding more routes.

4 Answers 4

3

Skipping FormRequest and using the validate method on the $request instance can achieve this. Laracasts even has a lesson on it.

public function store(Request $request) {
    $rules = [/*...*/];

    $attributes = $request->validate($rules);

    Model::create($attributes);

    return redirect(url('/'));
}
Sign up to request clarification or add additional context in comments.

3 Comments

This is what I have in mind but if possible, I would like to use just one function.
I rewrote the answer to use $request->validate instead. This might suite you.
Combining your suggestion with @Sletheren gives me an idea. Thank you to you both.
1

You can create a custom request:

php artisan make:request CustomRequest

This will generate this class:

class CustomRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return false;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            //
        ];
    }
}

The authorize() method will determine if the request can be validated in the first place.

The rules() method will return the validation rules for the current request.

And then in your controller function:

public function yourfunction(CustomRequest $request)

4 Comments

Hi @Sletheren, yes I know this. What I want to do is to validate a dynamic set of data. For example, Set of data1 required fields are firstname,middlename,lastname, then data2 required fields are firstname,lastname only. So what I have in mind is I would create data1Request and data2Request.
yes you can do that as well, you put a generic Request object, and then test with an if statement (example: if($request['type'] == 'data1') then execute a custom validation
Well, got some idea with what you've said. Thank you @Sletheren
Glad I could help :)
0

Step-1 Make a Trait

 public function store(Request $req)
{
    $model = (new $this->modelClass);

    $this->_modiformRequest($model, $req);

    $this->_makevalidateform($req);

    $savedModel = $this->_save($req, $model);

        return redirect()->route('web.dashboard'));
}

 protected function _modiformRequest($model, Request &$request)
{
    //
}

 protected function _rules($request, $id = null): array
{
    return [];
}


 protected function _makevalidateform($request, $id = null)
{
    $this->validate($request, $this->_rules($request, $id), $this->_ruleMessages($request, $id), $this->_ruleAttributes($request, $id));
}

Step-2 Make a controller

 protected function _rules($request, $id = null): array
    {
        if ($id) {
            return [
                'first_name' => 'required',
                'last_name' => 'required',
            ];
        }

        return [
            'first_name' => 'required',
            'last_name' => 'required',
            'password' => 'required',
        ];
    }

Comments

-2

In the validation rules you can simply add the "sometimes" rule. You can find it here https://laravel.com/docs/5.7/validation#conditionally-adding-rules

   public function rules()
{
    return [
    'firstname' => 'required',
    'middlename' => 'sometimes|required',
    'lastname' => 'required'
    ];
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.