Search code examples
phplaravelapivalidationlaravel-5.3

Right Way to validate form input fields


I'm building an API, one of the db table Person have 52 columns and most of them are required t don't think the way I'm doing is right

public function store() {
    if (! input::get('name') or ! input::get('age') or ! input::get('phone') or ! input::get('address') and so on till the 52 field) {
        return "Unprocessable Entity";
    }

    return "Validated";
}

And how to properly validate all the required fields

Thank You


Solution

  • You can simply write your validation rules and messages within a Request file and can call directly within your store function like as

    <?php
    
    namespace App\Http\Requests;
    
    use App\Http\Requests\Request;
    use Illuminate\Validation\Rule;
    
    /**
     * Class YourFileRequest
     * @package App\Http\Requests
     */
    class YourFileRequest extends Request
    {
    
        /**
         * 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' => 'required|unique:posts|max:255', 
               'body' => 'required',
            ];
        }
    
        /**
         * Get the custom validation messages that apply to the request.
         *
         * @return array
         */
        public function messages()
        {
            return [
               'title.required' => 'Please enter title', 
               'title.max' => 'Please enter max value upto 255', 
               'body.required' => 'Please enter body',
            ];
        }
    
    }
    

    within your controller

    use App\Http\Requests\YourFileRequest;
    
    
    ......
    
    
    public function store(YourFileRequest $request) 
    {
        //Your storing logic
    }