2

I have created a custom request that needs to check a variable before proceeding forward. This is my CustomRequest and have something like this

class CustomRequest extends FormRequest
{

    public function rules(){
        if ($variable == "abc") {
            return [
                "method"             => [
                    "required",
                    "in:mail",
                ]
            ];
        }
    }

}

And in my controller it is

public function addMethod(CustomRequest $request)
{
    //
}

I want that if the $variable is not equal to abc it just automatically fails and redirects the user back with message. I don't know how to do that.

Is there any possibility to achieve such functionality?

aynber
  • 22,380
  • 8
  • 50
  • 63
Ali Rasheed
  • 2,765
  • 2
  • 18
  • 31

2 Answers2

1

Add following function in your custom form request class.

public function authorize()
{
    return true;
}

Then it will work.

By default, it is set to false and we have to set it true manually.

Sagar Gautam
  • 9,049
  • 6
  • 53
  • 84
1

Just make a middleware, put it in the Kernel so that it can be applied for all routes and inside the middleware, you can check the variable value and take appropriate action.

Abhay Maurya
  • 11,819
  • 8
  • 46
  • 64
  • Hmm, this sounds interesting too. But I should be able to skip some routes after in web.php or controller? – Ali Rasheed Jun 12 '19 at 13:15
  • In that case you dont put it in kernet as global ones, just register it normally and then in your web.php, you can create a route group where you can apply this middleware to selected routes – Abhay Maurya Jun 12 '19 at 13:49