php 检查 Laravel 中的请求数组是否为空
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/42230304/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Checking if a request array is empty in Laravel
提问by prgrm
I have a dynamically generated form that gives me an array of inputs. However the array might be empty, then the foreach will fail.
我有一个动态生成的表单,它为我提供了一组输入。但是数组可能为空,然后 foreach 将失败。
public function myfunction(Request $request)
{
if(isset($request))
{
#do something
}
}
This obviously doesn't work since it is a $request object and is always set. I have no idea however how to check if there is any input at all.
这显然不起作用,因为它是一个 $request 对象并且总是被设置。但是,我不知道如何检查是否有任何输入。
Any ideas?
有任何想法吗?
回答by Saravanan Sampathkumar
A simple count check will do
一个简单的计数检查就可以了
if (count($request->all())) {
// foreach here.
}
回答by mbozwood
I always do this with my installations by adding a function to the Controller
in the App\Http\Controllers
directory.
我总是通过Controller
在App\Http\Controllers
目录中添加一个函数来对我的安装进行此操作。
use Illuminate\Http\Request;
public function hasInput(Request $request)
{
if($request->has('_token')) {
return count($request->all()) > 1;
} else {
return count($request->all()) > 0;
}
}
Rather self explanatory, return true if other input variables outside of the _token
, or return true if no token
and contains other variables.
不言自明,如果在 之外的其他输入变量,则_token
返回 true,如果没有token
并包含其他变量,则返回 true 。
回答by G. Cellie
Request class has a except()
method that includes everything except the key/keys defined. So:
Request 类有一个except()
方法,它包括除定义的键/键之外的所有内容。所以:
if ( !empty( $request->except('_token') ) )
execute the code when there is "something" in the request array.
当请求数组中有“东西”时执行代码。
回答by edcs
If you have a reference of the form inputs you're expecting, then Request::has()
might be a good method to use. Request::all()
could contain things like the XSRF token and would give you false positives.
如果您有所期望的表单输入的参考,那么这Request::has()
可能是一个很好的使用方法。Request::all()
可能包含诸如 XSRF 令牌之类的内容,并且会给您误报。