Home > Software design >  extract the month number from stored dates Laravel
extract the month number from stored dates Laravel

Time:06-01

I'm working on a project where users insert their workout every day . Each user can insert their workout date choosing from a calendar storing it in Exercise table in Date form. I've written this to calculate the workout days in the current month

DB::table('exercises')
 ->select('day')
 ->where('user_id', Auth::user()->id)
 ->whereMonth('day', date('m'))
 ->whereYear('day', date('Y'))
 ->distinct()
 ->get()
 ->count() 

and I want to display for each user the month with the highest workout days, I can do so with storing every month's workout days in a separate table but I don't know how to only extract the month from the dates already stored

CodePudding user response:

You can use Carbon e.g below

$month = Carbon::parse("2022/06/12")->format('MM');

you can read more about this at Carbon Documentations

CodePudding user response:

$month= date('M', strtotime($yourdate)

This should give you the month only from a stored date value. If you already have carbon installed and imported in your controller, I would suggest following @terinao given answer since it enhances a lot of features you would otherwise not find in standard php date functions.

CodePudding user response:

Try this solution

use Carbon\Carbon;
...

$current_month = Carbon::now()->format('m');
$current_year = Carbon::now()->format('Y');

DB::table('exercises')
    ->select('id', 'day')
    ->where('user_id', Auth::user()->id)
    ->whereMonth('day', $current_month)
    ->whereYear('day', $current_year)
    ->distinct()
    ->count();
  • Related