Reputation: 155
I'm trying to query data from btween two date from my date column. I tested using api
http://127.0.0.1:8000/api/expense?start=2019-08-01&2019-08-04
but its give me all the records not from date range?
My Controller
public function index(Request $request) { $user = auth()->user(); $expenses = Expense::whereHas('user', function($subQuery) use($user){ return $subQuery->where('shop_id', '=', $user->shop_id); })->with(['user'])->get(); if($request->start && $request->end) { $expenses->where(function($q) use ($request) { $q->whereBetween('date', array($request->start, $request->end)); }); } return ExpenseResource::collection($expenses); }
i think i do something wrong with my Controller, but i cant still figure it out..
Thanks in advances...
Upvotes: 1
Views: 883
Reputation: 1092
Hope this answer helps
public function index(Request $request)
{
$user = auth()->user();
$expenses = Expense::whereHas('user', function($subQuery) use($user){
return $subQuery->where('shop_id', '=', $user->shop_id);
})->with(['user']);
if($request->start && $request->end) {
$expenses->whereBetween('date', array($request->start, $request->end));
}
return ExpenseResource::collection($expenses->get());
}
what you did was you get()
the result first then you apply whereBetween()
.
Instead I applied whereBetween()
first then if your if
condition satisfied the get()
and change your URL to
127.0.0.1:8000/api/expense?start=2019-08-01&end=2019-08-04
Upvotes: 0
Reputation: 646
try something like this
$users = User::select("users.*")
->whereBetween('created', ['2018-02-01', '2018-02-10'])
->get();
Upvotes: 0