From the URL I am getting either a $filter
, $month
or both. When I for example want to show only results for November, everything works fine using the code below. But, when a filter has been set ALSO, then it shows all results (also from other months), if the filter has been found in the database.
What I want to achieve is, show only the results if the filter that was set has been found in the database, AND if a month has been set, only show the results from that particular month also.
My Section and Expense models have a belongsTo and hasMany relation respectively.
$query = Section::query();
If a filter has been set:
if ($filter !== 'false') {
$query->with(['expenses' => function ($query) use ($month) {
$query->where('date', 'LIKE', '%2015-' . Carbon::parse($month)->format('m') . '%');
}]);
}
If a month has been set:
if ($month !== 'false') {
$query->with(['expenses' => function ($query) use ($filter) {
$query->where('type', '=', $filter);
}]);
}
I also tried the following code:
if ($filter !== 'false') {
$query->with('expenses')->whereHas('expenses', function($query) use ($filter) {
$query->where('type', '=', $filter);
});
}
if ($month !== 'false') {
$query->with('expenses')->whereHas('expenses', function($query) use ($month) {
$query->where('date', 'LIKE', '%2015-' . Carbon::parse($month)->format('m') . '%');
});
}
$expenses = $query->orderBy('section', 'asc')->paginate(25);
I use a foreach on the $expenses
in my view to display the results.