Home > Blockchain >  How to show custom messages in laravel 5.8?
How to show custom messages in laravel 5.8?

Time:03-16

I am using laravel 5.8 version, i have one api which is responsible for registering ,i create one Request file which contains rules() and messages() function to display error messages but it's not throwing any error messages if any validation fails ,why this is happening can somebody explain ?

UserController.php

<?php

namespace App\Http\Controllers;

use App\Http\Requests\userRequest;
use App\UserSection;

class UserController extends Controller
{
    public function userRegister(userRequest $request){

        //logic of my code                    
        return response()->json($success);
    }
}

userRequest.php

<?php

namespace App\Http\Requests;

use App\Rules\CustomRule;
use Illuminate\Foundation\Http\FormRequest;

class userRequest extends FormRequest
{

    public function messages()
    {
        return [
            'first_name.required' => 'A title is required',
        ];
    }
    /**
     * 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 [
            'first_name' => 'string|required|max:25',
            'phone_number' => 'required|integer'
        ];
    }

}

The error i am facing when i hit the route without first_name key it's showing 404 not found error

CodePudding user response:

you might have missed headers part for taking the form-data

Accept = application/json

CodePudding user response:

As laravel docs

If validation fails, a redirect response will be generated to send the user back to their previous location. The errors will also be flashed to the session so they are available for display. If the request was an AJAX request, a HTTP response with a 422 status code will be returned to the user including a JSON representation of the validation errors.

So you need to specify the response type you expect, if you use postman for testing your api end point you have to add in request header Accept:application/json

<?php

namespace App\Http\Controllers;

use App\Http\Requests\userRequest;
use App\UserSection;

class UserController extends Controller
{
    public function userRegister(userRequest $request){
        //logic of my code                    
        return response()->json($success);
    }
}
  • Related