minaremonshaker's avatar

how can i validate a form with Get method usng FormRequest class?

hi I have implemented search and filter functionality in my project, and I want to validate the form using a Form Request class. The form has three parts:

A search input and a "Sort By" select field

Five "Search By" options

A submit button

What I need is a validation rule that triggers an error if the search input is not empty but none of the "Search By" options are selected. (Note: I’m using query strings for all of them.)

//controller 
    public function home(SearchFilterRequest $request){

/*        $searchQuery = $request->query('search') ?? '';

        $searchByQuery = $request->query('searchBy') ?? [];*/


/*        $users = User::filterdSearch($searchQuery, $searchByQuery)
            ->sort('first_name')
            ->get();*/
        $validation = $request->validated();

        return view("home");
    }
0 likes
7 replies
jlrdw's avatar

Normally a search will have the first request a post, and subsequent request are get.

jaseofspades88's avatar

I believe you need to use the beforeValidation method in your form request class, then extract the values from the query string. Something like this...

protected function prepareForValidation()
{
    $this->merge([
        'key' => $this->query('value'),
    ]);
}

The merge will add the values to the data to be validated.

JussiMannisto's avatar

may be because the FormRequests classes are made for all of the http verbs execluding Get requests

There's no difference in how form requests are handled on GET and POST requests. When you say it doesn't work, what exactly isn't working as you expect?

The name form request is a bit misleading. It's an agnostic class that encapsulates input validation, mutation, and authorization. It can be used with any request, including API calls.

You should use normal input methods when accessing input values. I suspect the raw query() method doesn't work with associative arrays.

- $request->query('searchBy')
+ $request->input('searchBy')

- if(empty($this->query('search')))
+ if(!$this->filled('search'))

There's also no need for two separate callback functions in the after() method. You can move those two if-statements into a single method and remove the other.

JussiMannisto's avatar
Level 50

@minaremonshaker I don't know why you would do that. The HTTP verb doesn't matter.

Fix the code instead. Don't try to read arrays with $request->query(). Use $request->input().

I assume that's your issue. You still haven't explained what in your code doesn't work.

There's also no need for the after() method. You can use normal validation rules like @ghabe suggested. It makes no difference if the input is in a query string or a POST body.

kashyapH's avatar

In your FormRequest, make searchBy nullable and add a check in after():

public function rules(): array
{
    return [
        'search' => 'nullable|string',
        'searchBy' => 'nullable|array',
        'searchBy.*' => 'string',
    ];
}

public function after(): array
{
    return [
        function (Validator $validator) {
            if (!empty($this->query('search')) && empty($this->query('searchBy'))) {
                $validator->errors()->add('searchBy', 'Please select at least one Search By option.');
            }
        }
    ];
}

This way, if the search box is filled but no checkbox is selected, validation will fail.

Please or to participate in this conversation.