'Show list of registered users base on current month using laravel
Im new to laravel and im tryin to learn the fundamentals of it. My question is how can I display all the registered users that is registered only on the current month.
Solution 1:[1]
$from = now()->startOfMonth(); // first date of the current month
$to = now();
$usersRegisetedThisMonth = User::whereBetween('created_at', [$from, $end])->get();
Solution 2:[2]
There is a simple way of doing it.
Just use this code
User::whereMonth('created_at', now()->month) // checking if the month of created_at is current month
->whereYear('created_at', now()->year) // checking if the year of created_at is current year
->get();
This line will give you Users from current month.
Solution 3:[3]
Nobody explained that these queries might be put in user model with local scope scopeWith magic method. I assume you read docs from top to bottom.
Simple example:
public function scopeRegisteredLastMonth($query){ return $query->whereBetween... }
You can specyficy additional arguments for this method.
The final call in controller will look like this:
$lastMonthUsers = User::registeredLastMonth()->get();
This function should be set to something like 'public function withRegisteredBetween($query, $date_start, $date_end) and return query based on date range.
PS: Don't use DB:: when you can use Model::method() or Model::query()->method()
PS2: for date management I advise you to install carbon, it's an additional addon - sometimes it's easy, sometimes not, overall not bad.
Solution 4:[4]
You could use the users
table with a whereBetween
clause like this:
$from = date('2022-01-05 00:00:00');
$to = date('2022-31-05 00:00:00');
$usersRegisteredThisMonth = DB::table('users')->
whereBetween('created_at', [$from, $to])->get();
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Mahmudul Hasan |
Solution 2 | Akhzar Javed |
Solution 3 | |
Solution 4 |