Reputation: 11
i have a table where all data of students. i need only less than month data of selected month of year. i have date column data like these.
registrationdate
2022-01-31
2021-12-01
2022-07-01
2021-11-12
2021-10-10
2022-01-07
2020-08-26
if I select month 12 and year 2021 I need only previous data of December 2021
$month=12 and $year =2021
$selectedmonthMalestudents = \DB::table('students')
->whereRaw('extract(month from registrationdate) = ?','<' [$month])
->whereRaw('extract(year from registrationdate) = ?', [$year])
->count();
Please Help me How to do these...
Upvotes: 1
Views: 539
Reputation: 378
First of all you should never use a Raw SQL statement in laravel, well except in some scenarios which it is absolutely necessary, because of security issues
so in your controller, you can use Carbon
public function index(Students $student) {
$date = Carbon::parse(' Decemeber of 2021 ');
$result = $student->where('registrationdate', '<', $date)->get();
return response()->json([compact('result'), 200]);
}
or use Laravel's Eloquent ORM Map collection method like
public function index(Students $student) {
$date = Carbon::parse(' Decemeber of 2021 ');
$result = $student->filter(function($std, $key) {
$created_at = Carbon::now($std['registration_date']);
if($create_at->isBefore($date)) {
return true;
}
})->get();
return response()->json([compact('result'), 200]);
}
Upvotes: 0
Reputation: 3240
All you need to call the whereMonth
and whereYear
method of eloquent. I have doubts whether that can work with DB::table but you can use the model anyway.
$selectedmonthMalestudents = \DB::table('students')
->whereMonth('salary_date', $month)
->whereYear('salary_date', $year)
->count();
personal suggestions:- always use model instead of DB::table();
Upvotes: 1