How to validate Route Parameters in Laravel 5?

后端 未结 4 1550
灰色年华
灰色年华 2021-02-12 18:23

As you know Laravel 5 changes the way you call the validator, the old way is calling the validator facade, but now there is the ValidatesRequests

4条回答
  •  有刺的猬
    2021-02-12 19:11

    Supposue the following route:

    Route::get('profile/{id}', 'ProfileController@show');
    

    You can still validate id parameter as L4 way:

    public function show(){
        $validator = \Validator::make(
            \Input::all(),
            [
                 'id' => ['required', 'numeric']
            ]
        );
    
        // run validator here
    }
    

    If you need to validate concrete data, take a look the following example:

    public function getUsername(Request $request, $username)
    {
        $validator = \Validator::make(
            [
                 'username' => $username
            ],
            [
                 'username' => ['required']
            ]
        );
    
        // run the validator here
    }
    

    L5 let you do in two other ways. The first one, using a generic Request class injected in the controller:

    public function show(Request $request){
        $this->validate($request, [
            'id' => ['required', 'numeric']
        ]);
    
        // do stuff here, everything was ok
    }
    

    In L5 you are allowed to call validate() functions that receive the request and the rules to run over it. This functions is in charge of run rules, if some rule fails, then the user is redirected to previous request

    Finally, as second option, you can use Form request validation. Remember, every GET and POST value can be accessed via Request class

提交回复
热议问题