Search code examples
phplaravellaravel-10

laravel validate $_GET parameters in URL


I'm on Laravel 10, and new to it too. Im trying to submit a form to a check() function that does some basic checks in db. Then it redirects the user to another route with $_GET data in the URL and to prevent the "POSTDATA warning because the refresh function wants to resend previous POST form data." warning on the check() function page.

here is the friendly url with the $_GET data {from?} and {search_string?}

Route::group(['middleware' => ['web']], function () {
  Route::post('/check', [SampleController::class, 'check'])->name('sample.check');
  Route::get('/order/{from?}/{search_string?}', [SampleController::class, 'order'])->name('sample.order');
}

this is my check() function

 public function check(Request $request) : RedirectResponse
    {

        $search_string = strtoupper(trim($request->search_string));
        $from = strtolower(trim($request->data_from));
        ...
        ...

        //if success redirect
        return redirect()->to(route('sample.order'), ['from' => $from, 'search_string' => $search_string]);
    }

and here is the order function

public function order(Request $request) 
    {
        $validator = Validator::make($request->route()->parameters(),[
            'from' => [
                'required',
                'string',
                'in:uk,us,id'
            ],
            'search_string' => [
                'required',
                'string',
                'max:255'
            ]
        ]);

        if ($validator->fails())
        {
            //abort(404, $validator->errors()); //this shows the json error message, how to make it show
            return view('samples::order')->withErrors($validator->errors());
        }

        
        return view('samples::order', ['from' => $request->from, 'search_string' => $request->search_string]);
    }

question is:

  1. is this the "laravel way" to validate the parameters in the url?
  2. is this how to to prevent the "POSTDATA warning" without using ajax?

Solution

  • For your first question, what do you mean by "Laravel way"? Laravel doesn't impose restrictions on how you validate your data; you can perform validation anywhere you need in the manner you prefer. However, alexeymezenin/laravel-best-practices recommends using Request classes for validations. You can discover more about best practices in that repository.

    For your second question, yes, you can prevent POSTDATA warnings by redirecting.