i'm trying to make validation in laravel but the code isn't returning in ajax here is my controller function :
public function postIndex(CategoryRequest $request ){
$request->store();
return ['status' => 'success' ,'data' => 'Data has been added successfully'];
}
and that's my request :
<?php
namespace App\Http\Requests;
use App\Category;
use Illuminate\Contracts\Validation\Validator;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\ValidationException;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Exceptions\HttpResponseException;
class CategoryRequest 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 [
'name_ar' => 'required',
'name_en' => 'required'
];
}
/**
* Get the validation messages
*
* @return array
*/
public function messages()
{
return [
'name_ar.required' => 'Please enter the name in arabic',
'name_en.required' => 'Please enter the name in english'
];
}
public function failedValidation(Validator $validator)
{
if ($validator->fails()){
return ['status' => 'error' ,'data' => $validator->messages()->getMessages()];
}
}
/**
* Store data function
*
*/
public function store()
{
$category = new Category();
if ($category->save()){
$category->details()->create([
'name' => $this->name_en,
'lang' => 'en'
]);
$category->details()->create([
'name' => $this->name_ar,
'lang' => 'ar'
]);
}
}
/**
*Edit data function
*/
public function edit($id){
$category = Category::find($id);
$category->english()->update([
'name' => $this->name_en
]);
$category->arabic()->update([
'name' => $this->name_ar
]);
}
}
i need to get the error messages using ajax but i don't know how to make it from request , i already can do it from the controller but i want my code to be clear so how can i do it ?