I want to validate the route parameters in the "form request" but don't know how to do it.
Below is the code sample, I am trying with:
Route
// controller Server
Route::group(['prefix' => 'server'], function(){
Route::get('checkToken/{token}',['as'=>'checkKey','uses'=> 'ServerController@checkToken']);
});
Controller
namespace App\Http\Controllers;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Http\Requests;
class ServerController extends Controller {
public function checkToken( \App\Http\Requests\CheckTokenServerRequest $request) // OT: - why I have to set full path to work??
{
$token = Token::where('token', '=', $request->token)->first();
$dt = new DateTime;
$token->executed_at = $dt->format('m-d-y H:i:s');
$token->save();
return response()->json(json_decode($token->json),200);
}
}
CheckTokenServerRequest
namespace App\Http\Requests;
use App\Http\Requests\Request;
class CheckTokenServerRequest extends Request {
//autorization
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
return [
'token' => ['required','exists:Tokens,token,executed_at,null']
];
}
}
But when I try to validate a simple url http://myurl/server/checkToken/222, I am getting the response: no " token " parameter set
.
Is it possible to validate the parameters in a separate "Form request", Or I have to do all in a controller?
ps. Sorry for my bad English.
The way for this is overriding
all()
method forCheckTokenServerRequest
like so:EDIT
Above solution works in Laravel < 5.5. If you want to use it in Laravel 5.5 or above, you should use:
instead.
You just missing the underscore before token. Replace with
wherever you check it against the form generated by laravel.
If you dont want to specify each route param and just put all route params you can override like this:
A trait can cause this validation to be relatively automagic.
Trait
Usage
Override the
all()
function on the Request object to automatically apply validation rules to the URL parametersAccess the data normally from the controller like this, after injecting the request:
The form request validators are used for validating HTML form data that are sent to server via POST method. It is better that you do not use them for validating route parameters. route parameters are mostly used for retrieving data from data base so in order to ensure that your token route parameter is correct change this line of your code, from
to
firstOrFail() is a very good function, it sends 404 to your user, if the user insert any invalid token.
you get
no " token " parameter set
because Laravel assumes that your "token" parameter is a POST data which in your case it is not.if you insist on validating your "token" parameter, by form request validators you gonna slow down your application, because you perform two queries to your db, one in here
and one in here
I suggest to use firsOrFail to do both validating and retrieving at once.