Iliyass Hamza
Iliyass Hamza

Reputation: 1405

How to validate Route Parameters in Laravel 5?

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 ?

Upvotes: 36

Views: 54974

Answers (7)

Ben Swinburne
Ben Swinburne

Reputation: 26467

When using a FormRequest you can merge the value from the URL into the input data by adding a prepareForValidation method to your class.

/**
 * Prepare the data for validation.
 *
 * @return void
 */
protected function prepareForValidation()
{
    // Add the url parameter id into the validation data
    // from a route such as /posts/{id}

    $this->mergeIfMissing(['id' => $this->id]); 
}

Upvotes: 1

Mahdyfo
Mahdyfo

Reputation: 1173

public function listTurns($doctor_id, $limit, $offset)
{
    $r = [
        'doctor_id' => $doctor_id,
        'limit' => $limit,
        'offset' => $offset,
    ];

    $validator = Validator::make($r, [
        'doctor_id' => 'required|numeric|min:1|exists:doctors,id',
        'limit' => 'required|numeric|min:1',
        'offset' => 'required|numeric|min:0',
    ]);
}

Upvotes: 4

jonshot
jonshot

Reputation: 805

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'
            ]
        ];
    }

Upvotes: 48

use Illuminate\Support\Facades\Validator;

public function getUsername($username) {
    $validator = Validator::make(['username' => $username], [
      'username' => 'required'
    ]);

    if ($validator->fails()) {
      return response()->json(['status' => 'error'], 400);
    }
}

Upvotes: -1

Elqolbi
Elqolbi

Reputation: 19

use Validator;

public function getUsername($username)
{
    $validator = Validator::make(['username' => $username], [
      'username' => 'required|string'
    ]);

    if ($validator->fails()) {
      return response()->json(['success' => false, 'errors' => $validator->messages()], 422);
    }
}

Upvotes: 0

Mitch
Mitch

Reputation: 135

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',
    ];
}

Upvotes: 10

manix
manix

Reputation: 14747

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

Upvotes: 4

Related Questions