Ali Rasheed
Ali Rasheed

Reputation: 2815

automatically failing custom request in laravel

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?

Upvotes: 2

Views: 100

Answers (2)

Abhay Maurya
Abhay Maurya

Reputation: 12277

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.

Upvotes: 1

Sagar Gautam
Sagar Gautam

Reputation: 9389

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.

Upvotes: 1

Related Questions