laravel request form the form class is verified

To simplify the controller parameter validation, we create a single folder, as we layer authentication parameters; specific exception is thrown, and Form 

First created in the app \ http folder a new file pieces Requests, into the newly created folder Requests, you can create a folder in the Nav, used to distinguish between different business functions. You can not create

In the newly created folder, create a class, for example NavRequest

<?php
 
namespace App\Http\Requests\Nav;
 
use Illuminate\Foundation\Http\FormRequest;
 
class NavRequest extends FormRequest
{
    public function authorize()
    {
        return true;
    }
 
    public function rules()
    {
        $rules = [
            'h5_id' => 'required |exists:h5_template,h5_id',
            'font_color'=>'string|nullable',
            'select_color'=>'string|nullable',
            'background_color'=>'string|nullable',
            'position'=>'int|required| between:0,1'
        ]; 
        Return  $ the rules ; 
    } 
 
    public  function messages () 
    { 
        $ Message = [
             'h5_id.required' => 'must be filled h5_id', 
            'h5_id.exists' => 'h5_id does not exist!', 
            'Position.required' = > 'Please select location!' 
        ]; 
        return  $ Message ; 
    } 
 
} 
// the first method: authorize (), controlling user access 
// second method: $ rules (), returns to verification array 
// third one method: $ message (), return a custom error messages

Then create a controller such as UserController

<? PHP 
namespace App \ Http \ the Controllers; 

use App \ Http \ Requests \ Nav \ NavRequest; 

public  function index (NavRequest $ Request )   // Request class uses just created 
    {
         $ the Data = $ Request -> All (); 
        dd ( $ Data ); 
    }

But this time there was a problem, no matter how kind, will not prompt an error message, but just do not meet the requirements to return home

Then we can rewrite this class method FormRequest

For example: Create a class that inherits FormRequest RequestController and method in which the rewrite

// 1. Here you can redefine a requestController class ,, 
// 2. Then let him inherit FormRequest, 
// 3. Finally rewrite failedvalidation method FormRequest this base class. Another way is to directly FormRequeste class may change the method of 
class RequestController the extends FormRequest { protected function failedValidation (the Validator $ Validator ) { $ error = $ Validator -> errors () -> All (); the throw new new HttpResponseException (Response () -> JSON ([ 'MSG' => 'error', 'code' => '500', 'Data' => $ error [0]], 500 )); } } so that when you parameters it can return an error message corresponding to the time not meet the requirements

 

Guess you like

Origin www.cnblogs.com/hanmengya/p/11486858.html