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
trait in base Controller class, but the validate
method accepts the request as the values array, but when you define your route parameters, these values are not stored in Request
, so how can I validate those parameters ?
Edit:
Route:
Route::get('/react-api/{username}', 'ProfileController@getUsername');
Controller:
public function getUsername(Request $request, $username) { $v = $this->validate($request, ['username' => 'required']); }
So, the question how can i validate this username parameter ?
Using where() method The where() method is defined on the route and it will take the param name and the validation that is applied on it.
Laravel routes are located in the app/Http/routes. php file. A route usually has the URL path, and a handler function callback, which is usually a function written in a certain controller.
Custom Validation Rule Using Closures $validator = Validator::make($request->post(),[ 'birth_year'=>[ 'required', function($attribute, $value, $fail){ if($value >= 1990 && $value <= date('Y')){ $fail("The :attribute must be between 1990 to ". date('Y').". "); } } ] ]);
Validation is the process of checking the incoming data. By default, laravel provides the base controller class that uses the ValidatesRequests trait to validate all the incoming Http requests.
If you plan to do this directly in your controller method you can do something like:
public function getUser(Request $request) { $request->merge(['id' => $request->route('id')]); $request->validate([ 'id' => [ 'required', 'exists:users,id' ] ]); }
To do this in a custom FormRequest
class, add the following:
protected function prepareForValidation() { $this->merge(['id' => $this->route('id')]); }
And in your rules
method:
public function rules() { return [ 'id' => [ 'required', 'exists:users,id' ] ]; }
Manix's answer wasn't working for me, I was having the same issues as Iliyass. The issue is route parameters aren't automatically available to the FormRequest. I ended up overriding the all() function in my particular FormRequest Class:
public function all() { // Include the next line if you need form data, too. $request = Input::all(); $request['username'] = $this->route('username'); return $request }
Then you can code rules as normal:
public function rules() { return [ 'username' => 'required', ]; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With