Hello: I am writing an api with Laravel.
When I try to use request validation in the controller, I get a 405 method not allowed. When I remove the request validation, everything runs smoothly.
Here is my route:
Route::post('product/create', 'Api\v1\ProductController@create');
Here is my controller:
<?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...';
}
}
Here is my request validator:
<?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.'
];
}
}
When I remove "CreateProduct $request" from the "create" method, everything works.
How can I use Laravel's request validation for api calls?
as @oseintow suggested:
if ($exception instanceof ValidationException) {
return response()->json(['errors'=>$exception->errors()], JsonResponse::HTTP_UNPROCESSABLE_ENTITY);
}Set validation in Product Controller.
public function create(Request $request)
{
$rules=array(
'title' => 'required',
'price' => 'required',
'short_description' => 'required'
);
$messages=array(
'title.required' => 'Please enter a title.',
'price.required' => 'Please enter a price.',
'short_description.required' => 'Please enter a short description.'
);
$validator=Validator::make($request->all(),$rules,$messages);
if($validator->fails())
{
$messages=$validator->messages();
$errors=$messages->all();
return $this->respondWithError($errors,500);
}
echo 'product created...';
}
I had the same problem when I was testing my API with PostMan. It turns out I was using the wrong Headers (Accept and Content-Type should be application/json but instead I was using the application/x-www-form-urlencoded for Content-Type).
After correcting that the custom request was working just fine.