phpjsonlaravellaravel-formrequest

how return validation rules and messages as JSON for API in laravel 8


I'm building an API and i want to validating the input fields with form requests .

i don't know how to return messages and rules as json in store method in controller

i want when fields is repetitious , or empty , be validated.

and when return $message and $rules json with return response()->json($message) gives error and says : TypeErrors : Arguments 2 passed , must be of the type array , object given

i check this link and It did not help https://laracasts.com/discuss/channels/laravel/how-to-send-validation-errors-as-json-to-view

my StoreCategoryRequest :


    public function rules()
    {

        $rules =  [
            'parent_id' => ['sometimes', 'required' , 'numeric'],
            'description'=>['required','max:500'],
            'status'=>['required'],
        ];

        if($this->method() == 'POST'){
            $rules['title'] = ['required','max:20', Rule::unique('categories')];
          }else{
            $rules['title'] = ['required','max:20' ,Rule::unique('categories')->ignore($this->category['id'])];
          }

           return $rules;
    }




    public function messages()
    {
        $message=[
            'title.unique'=>'عنوان نباید تکراری باشد',
            'title.required'=>'لطفا عنوان را وارد کنید',
            'title.max'=>'تعداد حروف عنوان نباید بیشتر از ۲۰ باشد',

            'description.required'=>'لطفا توضیحات را وارد کنید',
            'description.max'=>'تعداد حروف توضیحات نباید بیشتر از ۵۰۰ باشد',

            'status.required'=>'لطفا وضعیت مورد نظر خود را انتخاب کنید' ,


        ];

        return array_merge(parent::messages(), $message);

    }
}


this is my store method in CategoryController :

public function store(StoreCategoryRequest $request)
    {

        $validatedData = $request->all();
        $category = Category::create($validatedData);


        return response()->json([
        "success" => true,
        "message" => "successful",
        "data" => $category
        ]);

    }

thank you :***


Solution

  • It should not be necessary to pass the validation messages to the JSON response. When the validation fails Laravel will automatically return the response with the errors and not continue executing the code in the controller.

    There are pre-defined validation error messages that can also be localized. You can find them in resources/lang/en/validation.php - consider putting your custom messages there too.

    To retrieve the validation errors as JSON add in the header of the request the key Accept with the value application/json