简体   繁体   English

REST API后期验证Laravel 5.1

[英]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 routes.php文件

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

UserController.php 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. 我正在检查像这样$request->id!='' ,是否有任何验证规则或方法可以用来检查id是必填字段。

I have added this validation in my controller as well but what if id is not present how can I show the error? 我也已在控制器中添加了此验证,但是如果不存在id怎么办,如何显示错误?

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. $this->validate()方法旨在在验证失败时重定向回去,因此,您可以创建一个验证器实例并手动获取错误列表,而不是重定向到该方法。

use Validator;


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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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