5

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?

5 Answers 5

3

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...';
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, I am trying to remove all validation from controllers, reason being, my api and web uses the same validation and I am strictly using the DRY methodology as much as I can. So, I created my own validation classes with rules and messages methods which returns the same as a Request validator. I just inject them in the controller and use the Validator::make() and all validation rules/messages are kept out of the controllers.
2

as @oseintow suggested:

if ($exception instanceof ValidationException) {
    return response()->json(['errors'=>$exception->errors()], JsonResponse::HTTP_UNPROCESSABLE_ENTITY);
}

Comments

2

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.

Comments

0

Add this to your exception > handler.php > render method

if($exception instanceof \Illuminate\Validation\ValidationException){}

return parent::render($request, $exception);

Hope it helps

Comments

-1

just simply add ","

i think after this every thing run smoothly

this is how i use rules for code readability

https://pastebin.com/ivBEf7mT

 public function rules()
     {
         return [
            'title' => 'required',
            'price' => 'required',
            'short_description' => 'required',
         ];
    }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.