Nitish Kumar
Nitish Kumar

Reputation: 6276

Laravel custom form requests not validating

I'm have created a custom form request in my laravel 5.6 something like this:

<?php

namespace Noetic\Plugins\blog\Requests;

use Illuminate\Foundation\Http\FormRequest;

class StorePostRequest 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 [

        ];
    }
}

When I do not place anything in rules, I get the controllers working, and when I put any rule inside suppose I put

return [
    'title' =>  'required',
    'body'  =>  'required',
];

It works until it gets validated true, I mean if title and body is passed it gets validated, but when I don't send any data for title or body I'm not getting errors as response, I see the home page belonging to web middleware, I want to return the error data as response.

My controller is something like this:

public function store( StorePostRequest $request )
{
    if ($request->fails()) {
        return $this->errorResponse($request->errors()->all());
    }

    $data = $request->only('title', 'body');

    $post = Post::create($data);

    return response()->json(['post'=> $post ],200);
}

Help me out with these. Thanks

Upvotes: 0

Views: 2152

Answers (2)

Hamelraj
Hamelraj

Reputation: 4826

In your controller function you don't need to catch the validation just try with success path.

Handler will handle your validation

public function store( StorePostRequest $request )
{
    $data = $request->only('title', 'body');

    $post = Post::create($data);

    return response()->json(['post'=> $post ],200);
}

In your Handler

use Illuminate\Validation\ValidationException;

if ($exception instanceof ValidationException)
{
    return response($exception->errors())->header('Content-Type', 'application/json');
}

Upvotes: 1

Raja Hassan
Raja Hassan

Reputation: 15

use Illuminate\Contracts\Validation\Validator;

use Illuminate\Http\Exceptions\HttpResponseException;

after that

protected function failedValidation(Validator $validator) {
    throw new HttpResponseException(response()->json($validator->errors(), 422));
}

Upvotes: 0

Related Questions