Elegant selection of entries in the last 30 days

I have a list of records that have a date (for example, an 11/5/2013MDY form), but dates are fields VARCHAR.

I want to select all records for the last 30 days, but I don’t know how to relate them to the date format, since I get NULL in the date field.

I use Laravel and Eloquent ORM, how can I do this?

+4
source share
1 answer

You need an accessor in your model.

Suppose you have a field datesin your table.

public function getDatesAttribute($value)
   {
     $this->attributes['dates'] = Carbon::createFromFormat('m/d/Y', $value);
   }

The above function converts a date from a string to a Carbon object. By default, Laravel supports Carbon.

Now you have a controller:

$test = Test::where('dates', '>=', Carbon::now()->subMonth())->get();

I have not tested the code, but should work. :)

+12
source

All Articles