i'm building an API, i'm validating the input fields in my StoreLesson.php
public function rules()
{
return [
'title' => 'required',
'body' => 'required',
];
}
i'm using postman
to test the API, things are working fine but when i send POST request with empty fields, in postman
console in webview i'm getting redirected to welcom.blade.php
//LessonController.php
public function store(StoreLessons $request)
{
Lesson::create($request->all());
return response()->json($validator->errors(), 422); //i'm not getting any json with errors
//Lesson::create(input::all());
return $this->respondCreated('Lesson created successfully');
}
i want to display (return) the validator error as json
thank You
use the validator like this:
$validator = Validator::make($data, $rules);
if ($validator->fails())
return response()->json($validator);
Create StoreLessons Request inside app/Http/Requests.And call this request in LessonController.php you did.
----------
class StoreLessons extends Request
{
/**
* 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',
'body' => 'required',
];
}
/**
* @param array $errors
*
* @return JsonResponse
*/
public function response(array $errors)
{
return response($errors);
}
/**
* @param Validator $validator
*
* @return mixed
*/
protected function formatErrors(Validator $validator)
{
return $validator->errors()->all();
}