Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel - Show users from the last 30 days

I have a Laravel query that looks like this

$users = DB::table("users")
                   ->select('id')
                   ->where('accounttype', 'standard')
                   ->get()->all();

It is working and returning the id for all standard accounts, I am trying to limit it to only return results from the last 30 days, the date the user was created is stored as a timestamp in 'created_at'

Is it best to do this in the query or should I process the results afterwards?

like image 550
jsmitter3 Avatar asked Mar 17 '18 22:03

jsmitter3


3 Answers

You can use carbon along with the where clause:

use Carbon\Carbon;

$users = DB::table("users")
    ->select('id')
    ->where('accounttype', 'standard')
    ->where('created_at', '>', now()->subDays(30)->endOfDay())
    ->all();

As noted in the comments, do as much in the query as possible until you notice performance issues or your queries become unreadable.

like image 146
Chris Avatar answered Oct 03 '22 14:10

Chris


This works for me

    $thirty_days_ago = date('Y-m-d',strtotime("-31 days")); 
    $users_thirty_days_ago = User::where('accounttype', 'standard')->whereDate('last_online', ">=" , $thirty_days_ago)->count(); 
like image 34
Dankyi Anno Kwaku Avatar answered Oct 03 '22 13:10

Dankyi Anno Kwaku


You can use it

\App\Model::whereBetween('date', [now()->subdays(30), now()->subday()])->get();
like image 25
Mahedi Hasan Durjoy Avatar answered Oct 03 '22 12:10

Mahedi Hasan Durjoy