skip to Main Content

I m trying to filter my document on created_at with whereMonth/whereYear clauses. But it always returns empty collection. I can’t understand why.

Example :

$collection = MyModel::whereMonth('created_at', '06')->get();

I tried to change type of parameter with ‘6’ or (int) 6… but nothing changed.

Someone to explain me why it doesn’t work as documentation says (jenssegers package or laravel).
I didn’t found any solution…

Thank you.

2

Answers


  1. Chosen as BEST ANSWER

    Ok i found solution. I made my query in a whereRaw and used this :

    $month = (int) $request->month;    
    $queryMonth = [
       '$expr' => [
           '$eq' => [['$month' => '$created_at'], $month],
        ]];
    $collection = Model::whereRaw($queryMonth)->get();
    

    Same for requesting "year".

    Thanks for all.


  2. $collection = MyModel::all();
    
    foreach($collection as $result)
    {
    $datetime = $result->created_at;
    
    $date = CarbonCarbon::createFromFormat('Y-m-d H:i:s', $datetime);
    $month = $date->month;
    if($month == '06')
    {
    $collection = MyModel::whereMonth('created_at', $month)->get();
    }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search