简体   繁体   中英

What are the benefits of using Laravel Request Class in API's development?

Is there any benefit of using laravel requests classes for store and update methods in developing restful API's? Or do I have to make custom Validator::make response?

I have been facing difficulty in modifying the response format from failed requests as to follow some development standards requirements.

Can we modify the failed responses format from request class for API's?

I prefer to use independent from request class because there is at least one benefit: more clear code.

you can generate response as you wish like this (this is my solution, maybe there are more better solutions. i use this solution to return only one validation error not all. you can modify it as you wish):

in your Form request class add this method:

protected function failedValidation(Validator $validator)
    {
        $this->validator = $validator;

        foreach ($validator->messages()->getMessages() as $key => $value) {
            $first_messages_only[$key]  = $value[0];
        }

        throw new ValidationException($first_messages_only);
    }

and then in your Exception handler class, write this block of code in your render() method:

if ($exception instanceof ValidationException) {
            $response = [
                'status' => false,
                'message' => trans('api.general.validation_not_passed'), // $exception->getMessage()
                'data' => ['validation_errors' => $exception->validator]
            ];
            return response()->json($response);

        }

Since you asked its usage in API development then you can easily tell request class that you want json response by adding application/json header in your request then it will return json response.

Request class is best approach to validate incoming input from user which provides a lot of other features as well.

In Request class you can write validation rules for all request types eg get,post,put|patch or delete

You can allow or disallow anyone using authorize method based on your project logic.

You can write custom messages and send them custom error message bags.

If you write whole thing in a controller method then that will not be a good approach and difficult to manage while request class will make you comfortable while dealing with validations only.

protected $errorBag = 'custom_errors_bag'

public function authorize()
{
    return true;  //or any other logic here to authorize the user
}

public function rules()
{
    switch ($this->method()){
        case  'POST':
            return [
                'username' => 'required|string|max:20|unique:users',
                //...
            ];
        case 'PUT':
        case 'PATCH':
            return [
                'username' => 'required|string|max:20|unique:users,id',
                //...
            ];
        case 'DELETE':[
                'id' => 'required'
               //...
            ];
        default:break;
    }
}

public function messages()
{
    return [
        'username.required' => 'Please provide username',
        'username.unique' => 'Username must be unique',
        //...
    ];
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM