Search code examples
eloquentlaravel-5relationships

Laravel 5.2 get the closest date from eloquent collection


I have Eloquent Event model, which is related towards multiple dates like this:

$event->dates // shows Collection of 8 Eloquent date models

After that i need to pick the only date, what is closest to current time. I know how to do this using query of raw SQL, or DB class. But isnt there any better solution? I dont want to jump into database for data, I already have.

Date format in eloquent models is surprisingly string.


Solution

  • You can use what we call in laravel mutators like this ->

    <?php
    
    namespace App;
    
    use Illuminate\Database\Eloquent\Model;
    
    class Event extends Model
    {
        public function dates()
        {
            return $this->hasMany('Date');
        }
    
        /**
         * Get Dates for the event.
         *
         * @param  string  $value
         * @return array
         */
        public function getDates()
        {
            $dates = $this->dates()->getQuery()->orderBy('created_at', 'asc')->get();
            return $dates;
        }
    }
    

    Hope this helps.

    UPDATE

    I think now you can also directly do this in the model definition like this -

    return $this->hasMany('Date')->orderBy('created_at', 'asc')