Focus on PHP, MySQL, Linux and front-end development, interested in thank you for your attention!! Article collated in GitHub, mainly includes PHP, Redis, MySQL, JavaScript, HTML&CSS, Linux, Java, Golang, Linux and tool resources related theoretical knowledge, interview questions and practical content.

The problem background

Recently, the laravel framework was used in the company’s project development, which adopted the front and back end development model. Anyone who has worked with front and back end development should know that the format of the data returned from the back end needs to be as consistent as possible so that the front end can handle it as well. Let’s start by looking at the following two images of the interface returned by the effects, so that it may be more intuitive.

Maybe you don’t see the difference between the two charts above. Let me put it in words here.

This is what happens when Laravel does form validation. When the front end sends a POST request to my back-end interface, it sends a title and body field. My backend needs to do some non-null validation for both fields. If you follow the framework manual, the output format is the one shown in Figure 1. Then the unified output format of the back-end is the format in Figure 2, if the output format in Figure 1 is definitely not, so we need to do a special processing.

Troubleshoot problems

First of all, we can see the following information through the documentation. In the underlined section below, the return message is that all unvalidated data is returned to the front end in the data format shown in Figure 1.

The desired effect

We know from Figure 3 that Laravel by default returns an HTTP status code with 422 and returns all validation errors.

However, all we need is the format shown in Figure 2, with a single output error message. The general idea is that when output, we default to display the first failed validation, when passed, before the second failed to become the first, so that the loop, each of our data is verified. For validation, we choose where the framework exception is handled uniformly, so that each validation is handled automatically.

The solution

The framework is written with Larave 5.8 in mind. If the version is different, special processing may be required, but the idea of processing can be referred to below.

1. Create a form validator. After executing the following command, we should see this file in the PHP app/Http/Requests directory.


php artisan make:request ProjectValidate

Copy the code

2. Define authentication rules. The rules method defines the validation rules, while the Messages method defines the error message returned. This method can also be omitted so that the message displayed is in English rather than the Chinese seen in Figure 1 or figure 2.


namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;

class ProjectValidate 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 [
        'title'= >'bail|required'.'body'= >'required',]; }/**
    * define the validation message
    *
    * @return array
    */
    public function messages()
    {
        return [
        'title.required'= >'Article title required'.'body.required'= >'Article Content required',]; }}Copy the code

3. Use the validator. Here I define a controller that uses dependency injection to validate data in the addData method. Remember that the method body is not executed without data validation.


namespace App\Http\Controllers\Backend\Project;

use App\Http\Requests\ProjectValidate;
use App\Http\Controllers\Backend\UCenter;

class Index extends UCenter
{
    public function index()
    {
        return success();
    }

    public function addData(ProjectValidate $request)
    {
        $validated = $request->validated();
        return success($validated); }}Copy the code

4. Unify the data format. Find the PHP App\Exceptions\ handler. PHP file, find the following method, and change it to the following. At this point in the form validation will display the format information in Figure 2.

public function render($request.Exception $exception)
{
    if ($exception instanceof ValidationException) {

    / / way

    $message = $exception->validator->getMessageBag()->first()

    2 / / way

    // Only the first error message is read
    $errors = $exception->errors();
    $message = ' ';
    // The frame returns a two-dimensional array, so we need to loop through the first data
    foreach ($errors as $key= >$val) {
        $keys = array_key_first($val);
        $message = $val[$keys];
        break;
    }
    return response()->json(['code'= >1001.'message'= >$message.'data'= > []].422);
    }
    return parent::render($request.$exception);
}
Copy the code

conclusion

1. The advantage

The output is in a fixed format, and the front end does not need to make special formatting adjustments when processing data.

2. Disadvantage

In this way, each time you authenticate, an HTTP request is sent to the backend.