您好:我正在使用Laravel编写api。Laravel API请求验证
当我尝试使用请求验证控制器,我得到不允许405方法。当我删除请求验证时,一切都运行平稳。
这里是我的路线:
Route::post('product/create', 'Api\v1\[email protected]');
这里是我的控制器:
<?php
namespace App\Http\Controllers\Api\v1;
use App\Http\Requests\CreateProduct;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Handlers\Products;
use Illuminate\Support\MessageBag;
class ProductController extends Controller
{
/**
* Create Product.
*/
public function create(CreateProduct $request)
{
echo 'product created...';
}
}
这里是我的要求验证:
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class CreateProduct 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 [
'title' => 'required',
'price' => 'required',
'short_description' => 'required'
];
}
/**
* Set custom validation messages.
*
* @return array
*/
public function messages()
{
return [
'title.required' => 'Please enter a title.',
'price.required' => 'Please enter a price.',
'short_description.required' => 'Please enter a short description.'
];
}
}
当我删除从 “CreateProduct $请求” “创建”方法,一切正常。
如何使用Laravel的api调用请求验证?
谢谢,我想从控制器中删除所有验证,原因是,我的api和web使用相同的验证,我严格使用DRY方法如我所能。所以,我使用规则和消息方法创建了自己的验证类,它们与Request验证程序的返回值相同。我只是将它们注入控制器并使用Validator :: make(),并将所有验证规则/消息保存在控制器外面。 –