Laravel 5如何验证路由参数? [英] Laravel 5 how to validate route parameters?
问题描述
我想验证表单请求"中的路由参数,但不知道如何做.
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:
路线
// controller Server
Route::group(['prefix' => 'server'], function(){
Route::get('checkToken/{token}',['as'=>'checkKey','uses'=> 'ServerController@checkToken']);
});
控制器
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']
];
}
}
但是当我尝试验证简单的URL http://myurl/server/checkToken/222 ,我得到的回应是:no " token " parameter set
.
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.对不起,我的英语不好.
ps. Sorry for my bad English.
推荐答案
对于Laravel< 5.5:
这样做的方法是像这样覆盖CheckTokenServerRequest
的all()
方法:
For Laravel < 5.5:
The way for this is overriding all()
method for CheckTokenServerRequest
like so:
public function all()
{
$data = parent::all();
$data['token'] = $this->route('token');
return $data;
}
编辑
对于Laravel> = 5.5:
上述解决方案在 Laravel<中工作. 5.5 .如果要在 Laravel 5.5或更高版本中使用它,则应使用:
EDIT
For Laravel >= 5.5:
Above solution works in Laravel < 5.5. If you want to use it in Laravel 5.5 or above, you should use:
public function all($keys = null)
{
$data = parent::all($keys);
$data['token'] = $this->route('token');
return $data;
}
相反.
这篇关于Laravel 5如何验证路由参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!