We are trying to build and api with our project. My problem is when I need to get a specific event which has a column date_from
and date_to
it always gets the data even if the event was finished. I want to get the specific event that is been for the rest of the two dates. My thing is when the date_from
and the date_to
equal or grater than the date today, It will show and after the date is finished it will not. Here are some of my codes.
Index
public function index(Request $request) { $person = User::find(Auth::user()->id); $now = Carbon::now()->toDateString(); if(empty($person)) return response()->json([ 'code' => '03', 'status' => 'Invalid User' ], 403); $role = $person->role; if ($role == 2 || $role == 3) { $level = Event::active()->with(['groups']) ->where('school_id', '=', $person->school_id) ->where('group_id', '=', $role) ->orWhere('group_id', '=', $person) ->where('status', '=', 1) ->where('active', '=', 1) ->whereRaw("date_from <= date('$now')") ->whereRaw("date_to >= date('$now')") ->get(); return response()->json($level); }
Result in Postman
{ "id": 1, "name": "Final", "content": "<p>Sample</p>", "group_id": 2, "event_date": "2019-09-01", "date_from": "2019-09-20", //sept 20, 2019. The event started "date_to": "2019-10-03",//oct, 3 2019. The event end date. still gets the data even the date was not today. "time_from": "16:15:00", "time_to": "22:15:00", "event_place": "Room", "image": "", "school_id": 1, "smsnotify": 0, "appnotify": 1, "status": 1, "active": 1, "updated_by": null, "created_at": "2019-09-27 08:29:13", "updated_at": "2019-10-04 06:18:43", "users_id": 2, "groups": { "id": 2, "name": "Teachers", "description": "Teachers", "updated_by": null, "created_at": null, "updated_at": null } }
Advertisement
Answer
The variable $now
, as you have defined it, should already be the date only component of the current timestamp. So there should be no reason not to use regular where()
:
$now = Carbon::now()->toDateString(); $level = Event::active()->with(['groups']) ->where('school_id', '=', $person->school_id) ->whereIn('group_id', [$role, $person]) ->where('status', '=', 1) ->where('active', '=', 1) ->where('date_from', '<', $now) ->where('date_to', '>=', $now->addDays(1))
I am assuming in my answer that you want to avoid today. The logic for this is that the date is earlier than today’s date at midnight, or on or after midnight of tomorrow.
Besides the date issue, your handling of the group_id
using where()
and orWhere()
might have been causing problems. Your intention in SQL is the following:
WHERE (group_id = $role OR group_id = $person)
Note carefully the parentheses. But, as you wrote it, because of order of operations it might come out not as you intended.