Search code examples
phplaraveleloquentlaravel-5.1laravel-collection

Filter a laravel collection inside a view by comparing dates?


I am trying to filter a collection of objects by comparing date its expiry date with today's date but I cant quite get it to work. Can anyone take a look at the code. I'm sure i'm missing something here. I have searched all over and found alot of examples but none are working.

This complies just fine but with a list of 9 objects 3 of which have an expiry date which is set to 2012 it doesn't return any results from the collection.

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

Solution

  • Access the value expired_on directly

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

    You can make the expired_on property a Carbon instance by default by adding it to the $dates array in your model:

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

    now expired_on always returns a Carbon instance