繁体   English   中英

在Laravel中处理空口才好的最佳做法是什么?

[英]What is the best practice to handle empty eloquent query in Laravel?

到目前为止,我正在使用雄辩的->exist()和纯PHP的isset() ...

现在,我正在使用它们两者...,当其中一个不起作用时,我将切换到另一个,然后它将起作用。

但这会使代码看起来很脏。.您对何时使用它们有什么建议吗?有什么区别。.在laravel中处理空口雄辩查询的最佳实践是什么。.谢谢

我们可以为此使用empty()方法。

// After you initiate your model in variable
$var = Model::find($id);

// Just check it use empty method 
if(empty($var)) {
   // Do something here
}

编辑:在最佳实践中,使用native native exists()isset()

众所周知, isset方法通常用于检查变量是否已定义。

$col = "column"
if(isset($col)) {
   // true
}
if(isset($cols)) {
   // else
}

对于exists() ,通常用于验证。 您可以在laravel文档中进行检查。

$name = $request->get('name');
if(User::where('name', $name)->exists()){
  // It will true if the in users table exists the $name in name columns
  // And do something if true :D
} else {
  // If not exists/false you can return error like this

  return response()->json([
      'error'=>true
  ],400);
}

暂无
暂无

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

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