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.
CodePudding user response:
$collection = MyModel::all();
foreach($collection as $result)
{
$datetime = $result->created_at;
$date = \Carbon\Carbon::createFromFormat('Y-m-d H:i:s', $datetime);
$month = $date->month;
if($month == '06')
{
$collection = MyModel::whereMonth('created_at', $month)->get();
}
}
CodePudding user response:
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.