PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Tuesday, February 1, 2022

[FIXED] Laravel L5.5 dynamic request validation that depends on variable

 February 01, 2022     laravel, laravel-5, php, validation     No comments   

Issue

In my controller, I have something like that:

switch ($type)
    {
        case '1':
            $validation_rules = [
                'a' => 'required',
                'b' => 'required',];
            break;
        case '2':
            $validation_rules = [
                'd' => 'required',
                'j' => 'nullable|numeric',];
            break;
        case '3':
            $validation_rules = [
                't1.x' => 'required|numeric',
                't1.y' => 'required|numeric',];
            break;
    }

$request->validate($validation_rules);

But I dont like this because it mass up my controller. I am looking for a way to use request validation instead.

Something like that would be my target:

public function store(XXRequest $request)

And put the logic for the validation inside.


Solution

Create a new request file:

php artisan make:request SomeRequest

Put the logic into the rules() method:

public function rules()
{
    switch ($this->type)
        {
            case '1':
                $validation_rules = [
                    'a' => 'required',
                    'b' => 'required',];
                break;
            case '2':
                $validation_rules = [
                    'd' => 'required',
                    'j' => 'nullable|numeric',];
                break;
            case '3':
                $validation_rules = [
                    't1.x' => 'required|numeric',
                    't1.y' => 'required|numeric',];
                break;
        }

    return $validation_rules;
}

Then use it:

public function store(SomeRequest $request)

https://laravel.com/docs/5.5/validation#form-request-validation



Answered By - Alexey Mezenin
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing