Làm việc với request trong api

Làm việc với request trong api

Bình thường chúng ta sẽ làm việc với request 1 cách đơn giản khi trả về $errors nếu sài blade nhưng khi dùng với api thì chúng ta cần custom 1 chút với hàm failedValidation

<?php

namespace App\Http\Requests;

use App\Rules\PhoneRule;
use Illuminate\Contracts\Validation\Validator;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Http\Exceptions\HttpResponseException;
use Illuminate\Validation\ValidationException;

class StoreApiUserRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     */
    public function authorize(): bool
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array<string, \Illuminate\Contracts\Validation\Rule|array|string>
     */
    public function rules(): array
    {
        return [
            'phone' => ['required','unique:users,phone',new PhoneRule()],
        ];
    }
    public function messages()
    {
        return ([

            'phone.min' => 'Số không được nhỏ hơn 10',
            'phone.required' => 'Không có số điện thoại',
            'phone.unique' => 'Số điện thoại đã tồn tại',
        ]);
    }
    
    protected function failedValidation(Validator $validator)
    {
        throw new HttpResponseException(response()->json([
            'success' => false,
            'message' => 'Validation errors',

            'data'=>$validator->errors(),
        ]));
    }
    
}

Ở đây chúng ta khi sử dụng sẽ có dạng như sau khi gọi api về: