如何检查对象中的必填字段?

时间:2018-06-10 14:44:58

标签: php laravel validation object

我有带字段的示例对象

name => John
surname => Dow
job => engineer

并使用占位符输出表单。一些是必需的,一些不是。

检查是否需要检查以及是否显示空字段错误的最佳做法是什么?

2 个答案:

答案 0 :(得分:0)

我认为"简单是最好的",只是通过对象并检查属性是否存在

参考:property_exists

示例:

if (property_exists($object, 'name')) {
     //...do something for exists property 
} else {
     //...else
}

答案 1 :(得分:0)

实际上你可以通过多种方式在控制器方法中做到这一点,或者为我使用Laravels Request Classes,我更喜欢使用Request Classes

看下面我将列出两个例子

  1. 在控制器的方法内验证

    public function test(Request $request){
        if($request->filled('name){
             /*filled will check that name is set on the current 
               request and not empty*/
    
             //Do your logic here 
        }
    }
    
  2. 第二种方法是使用控制器内的Validator Facade

    use Validator;
    
    class TestController{
         public function test(Request $request){
           $validator = Validator::make($request->all(), [
             'title' => 'required|unique:posts|max:255',
             'body' => 'required',
           ]);
    
          /*continue with your logic here if the request failed on 
            validator test Laravel will automatically redirect back 
            with errors*/
         }
    }
    
  3. 我最喜欢的第三种方式

    您可以使用此命令生成Request类

    php artisan make:request AddBookRequest
    

    将在“app / Http / Requests / AddBookRequest”下生成请求类,在任何生成的请求类中,您将找到两个方法authorize()和rules()

  4. 在授权方法中你必须返回truthy或falsy值,这将检测发出请求的当前用户是否有权在规则方法中触发此请求,就像你在第二种方式中在Validator中那样做检查示例

        public function authorize(){
             return true;
        }
    
        public function rules(){
            return [
                'title' => 'required|string',
                'author_id' => 'required|integer'
            ];
        }
    

    然后只需在你的控制器中就可以像这样使用生成的请求

        use App\Http\Requests\AddBookRequest;
    
        public function store(AddBookRequest $request){
            /* do your logic here since we uses a request class if it fails 
            then redirect back with errors will be automatically returned*/
        }
    

    希望这有助于您了解有关验证的更多信息 https://laravel.com/docs/5.6/validation