0

I have to pass an array for whereMonth..

$months = ['01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12'];

$user_date = UserDetails::where('userId', '=', $id)
    ->whereMonth('created_at', $months[1])
    ->whereYear('created_at', date('Y'))
    ->pluck('date');
Jignesh Joisar
  • 13,720
  • 5
  • 57
  • 57
Ashwini
  • 3
  • 2

2 Answers2

2

You need to used the whereRaw Method here

$months = [1,2,3,4,5,6,7,8,9,10,11,12];

$user_date = UserDetails::selectRaw("*,MONTH(created_at) as month_at")
    ->where('userId', '=', $id)
    ->whereRaw('MONTH(created_at) in ('.implode(',',$months).')')
    ->whereYear('created_at', date('Y'))
    ->pluck('date');
Jignesh Joisar
  • 13,720
  • 5
  • 57
  • 57
0

To Avoid Raw Expressions You can use Virtual Columns

1.Add this to your Migration after created_at column

$table->char('created_at_month',3)->virtualAs('DATE_FORMAT(created_at,"%m")');

Run your Migrations

Now You can Run the following query to get the records that is created at specific month

$months = ['01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12'];

$user_date = UserDetails::where('userId', '=', $id)
    ->whereIn('created_at_month', $months)
    ->whereYear('created_at', date('Y'))
    ->pluck('date');

If you want to Know more check the Below links

  1. https://laravel.com/docs/8.x/migrations#column-modifiers
  2. https://www.w3schools.com/sql/func_mysql_date_format.asp
ManojKiran A
  • 5,896
  • 4
  • 30
  • 43
  • This will over complicate the whole table just for a single filter that I believe shouldn't be suggested to user unless there is a valid requirement to introduce such change, the solution posted by @Jignesh Joisar is far better than this – M Khalid Junaid Feb 09 '21 at 16:51
  • I have Clearly Mentioned that if you want to avoid raw expressions and increase the performance he can use my solution @M Khalid Junaid – ManojKiran A Feb 10 '21 at 05:04