我正在尝试在laravel中进行验证但是代码没有在ajax中返回这里是我的控制器函数:
public function postIndex(CategoryRequest $request ){
$request->store();
return ['status' => 'success' ,'data' => 'Data has been added successfully'];
}
那是我的要求:
<?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
]);
}
}
我需要使用ajax获取错误消息,但我不知道如何从请求中获取它,我已经可以从控制器执行此操作但我希望我的代码清楚,所以我该怎么办?
答案 0 :(得分:0)
protected function formatErrors(Validator $validator)
{
$result = ['status' => 'error' ,'data' => implode(PHP_EOL ,$validator->errors()->all())];
return $result;
}
public function response (array $errors) {
return response()->json($errors, 200);
}
我添加它们后,错误现在显示在ajax
中