我想使用以下代码计算我得到的输出:
{{ $kentekens->where('created_at', '>=', Carbon::today()) }}
这给出了String中的输出,但我想要计算它获得的匹配数量。 我尝试了以下但没有成功:
{{ $kentekens->where('created_at', '>=', Carbon::today()->count()) }}
{{ $kentekens->count()->where('created_at', '>=', Carbon::today()) }}
public function create() {
$kentekens = Kenteken::latest()
->get();
return view('layouts.dashboard', compact('kentekens'));
}
class Kenteken extends Model {
protected $table = "kenteken";
}
有人有任何想法吗?
答案 0 :(得分:2)
正确的语法是:
{{ $kentekens->where('created_at', '>=', Carbon::today())->count() }}
答案 1 :(得分:0)
问题1
一种解决方案是将两个变量添加到控制器的视图中:
<强>控制器强>
public function create() {
$kentekensQuery = Kenteken::latest()->where('created_at', '>=', Carbon::today());
return view('layouts.dashboard')
->with('kentekens', $kentekensQuery->get())
->with('kentekensCount', $kentekensQuery->count());
}
查看强>
{{ $kentekens }}
{{ $kentekensCount }}
但是这个方法会产生两个sql请求:第一个获取项目,第二个计算项目。
更好的解决方案可能是仅将第一个请求的结果作为Collection返回,并在该集合上调用count()方法。事实是在Eloquent模型查询构建器上调用的get()方法返回一个Collection。 \ O /
<强>控制器强>
public function create() {
$kentekens = Kenteken::latest()->where('created_at', '>=', Carbon::today();
return view('layouts.dashboard')
->with('kentekens', $kentekens->get());
}
查看强>
{{ $kentekens }}
{{ $kentekens->count() }}
问题2
使用上述第一个解决方案:
<强>控制器强>
$kentekensQuery = Kenteken::latest()
->where('created_at', '>=', Carbon::today())
->where('kenteken', 'LIKE', 'B%');
使用第二个解决方案,正如@Alexei Mezenin所说,你必须使用一个闭包,一个函数运行,同时用函数迭代集合上的每个值,这里是filter()函数:
查看强>
{{
$kentekens->filter(function ($value, $key) {
return strpos($value, 'B') === 0;
});
}}