首页 文章

通过比较日期过滤视图内的laravel集合?

提问于
浏览
2

我试图通过比较日期的到期日期和今天的日期来过滤一组对象,但我不能让它工作 . 任何人都可以看看代码 . 我确定我在这里遗漏了一些东西 . 我已经搜遍了所有的例子但发现了很多例子,但都没有 .

这符合得很好,但有一个包含9个对象的列表,其中3个有效期限设置为2012,它不会从集合中返回任何结果 .

Controller

public function classifieds()
{   
    $myclassifieds = Auth::user()->classifieds;
    return view('account.classifieds')->with(['allclassifieds'=>$myclassifieds]);
}

View

@if(count($allclassifieds->where('expired_on','<', Carbon\Carbon::now() ) ) > 0)
//Something here
@endif

1 回答

  • 1

    直接访问值 expired_on

    @foreach($allclassifieds as $classified)
        @if($classified->expired_on > Carbon\Carbon::now())
            // show classified
        @endif
    @endforeach
    

    您可以将expired_on属性默认设置为Carbon实例,方法是将其添加到模型中的 $dates 数组中:

    protected $dates = ['created_at', 'updated_at', 'expired_on'];
    

    现在 expired_on 总是返回一个Carbon实例

相关问题