我想在Request验证类中验证路由参数。我知道这个问题已经被问过很多次了,但是According to this question我重写了all()
方法,并且收到了这个错误:
Class App\Http\Requests\DestroyUserRequest does not exist
我正在使用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()方法有什么问题?
答案 0 :(得分:1)
您得到的错误似乎很奇怪。我相信问题出在这里,因为您的方法签名与父代签名不同。
应该是:
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中进行了更改。您可以阅读upgrade guide:
所有方法
如果要覆盖Illuminate \ Http \ Request的all方法 类,您应该更新方法签名以反映新的 $ keys参数:
公共函数all($ keys = null){