Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Eloquent select records form last 30 days

I having a list of records that have a date (like 11/5/2013, that's a MDY formt), but the dates are VARCHAR fields.

I want to select all the records that are in the last 30 days, but don't know how to cast them to date format, as I get NULL in dates field.

I'm using Laravel and Eloquent ORM, how can I accomplish this?

like image 598
jOpacic Avatar asked Dec 01 '22 17:12

jOpacic


1 Answers

You need an accessor in your model.

Assume your have a dates field in your table.

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

The above function will convert the date from string to Carbon object. By default Laravel support Carbon.

Now from you controller:

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

I haven't tested the code but should work. :)

like image 172
Anam Avatar answered Dec 11 '22 10:12

Anam