Laravel 5.7-覆盖请求验证类中的all()方法以验证路由参数? [英] Laravel 5.7 - Override all() method in Request validation Class to validate route parameters?
问题描述
我想在Request验证类中验证路由参数.我知道这个问题已经被问过很多次了,但是根据这个问题我重写all()
方法,并收到此错误:
I want to validate the route parameters in the Request validation class. I know this question has been asked many times before but According to this question I override all()
method and I receive this error:
Class App\Http\Requests\DestroyUserRequest does not exist
我正在使用Laravel 5.7.
I'm using Laravel 5.7.
路线:
Route::delete('/user/{userId}/delete', 'UserController@destroy')->name('user.destroy');
控制器:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests\DestroyUserRequest;
use App\User;
class UserController extends Controller
{
/**
* Remove the specified resource from storage.
*
* @param int $id
* @return Response
*/
public function destroy(DestroyUserRequest $request)
{
User::find($request->route('userId'))->delete();
return $request->route('userId');
}
}
DestroyUserRequest:
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class DestroyUserRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
return [
'userId' => 'integer|exists:users,id'
];
}
public function all()
{
$data = parent::all();
$data['userId'] = $this->route('userId');
return $data;
}
}
重写all()方法有什么问题?
What is wrong to override all() method?
推荐答案
您得到的错误似乎很奇怪.我认为问题出在这里,因为您的方法签名与父代签名不同.
The error your get seems to be quite strange. I believe the problem is here because your method signature is not the same as parent.
应该是:
public function all($keys = null)
{
$data = parent::all($keys);
$data['userId'] = $this->route('userId');
return $data;
}
因为Illuminate/Http/Concerns/InteractsWithInput.php
的签名是:
/**
* Get all of the input and files for the request.
*
* @param array|mixed $keys
* @return array
*/
public function all($keys = null)
在Laravel 5.5中进行了更改.您可以阅读升级指南:
The change was made in Laravel 5.5. You can read in upgrade guide:
所有方法
如果要覆盖Illuminate \ Http \ Request的all方法 类,您应该更新方法签名以反映新的 $ keys参数:
If you are overriding the all method of the Illuminate\Http\Request class, you should update your method signature to reflect the new $keys argument:
公共函数all($ keys = null){
public function all($keys = null) {
这篇关于Laravel 5.7-覆盖请求验证类中的all()方法以验证路由参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!