简体   繁体   中英

REST API post field validation Laravel 5.1

I need to check if I have all posted variables are required or else throw error. Till Now I am doing like this

Routes.php

Route::post('/api/ws_fetchuser', 'UserController@fetch_user_details');

UserController.php

<?php

namespace App\Http\Controllers;

use App\Http\Requests;
use Illuminate\Http\Request;
use App\User;

class UserController extends Controller
{
  public function fetch_user_details(Request $request)
    { 
        if(!empty($request) && $request->id!='')
        {
            print_r($request->id);    
        }
        else
        {
            return response(array(
            'error' => false,
            'message' =>'please enter all form fields',
            ),200);        
        }

    }
}

I am checking like this $request->id!='' , is there any validation rules or methods which I can use to check id is required field.

I have added this validation in my controller as well but what if id is not present how can I show the error?

Updated Validation Code:

public function fetch_user_details(Request $request)
    { 
        $this->validate($request, [
        'id' => 'required'
        ]);

        print_r($request->id);

    }

$this->validate() methods designed to redirect back when validation failed, So instead of that you can create a validator instance and get the error list manually.

use Validator;


$validator = Validator::make($request->all(), [
        'id'    => 'required'
    ]);

if ($validator->fails()) {
    return json_encode($validator->errors()->all());
}

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