Home > Software design >  Laravel 8.73 - check if date has passed and skip loop
Laravel 8.73 - check if date has passed and skip loop

Time:11-28

This is the idea of the filtering I need to do:

if ($course == 'specific-course') {
    $view = 'pages.course.specifc-course';
    $id = '8';
}

// get current date and time
$currentDate = date('Y-m-t h:m:s');

// get the course data from the database
$events = DB::table('eventaries')->where('category', $id)->get();

// HERE I NEED TO IMPLEMENT A WAY TO CHECK IF THE
// START OF THE EVENT HAS ALREADY PASSED AND
// THEN SKIP THE COURSE
foreach ($events as $event) {
    if ($event->start > $currentDate) {
        return view($view, [
            "events" => $events,
        ]);
    }
}

It grabs events from the database table eventaries and then gives out all based on the specifc $id aka. menu item of the website. But there is currently no way to filter if an event start date has passed the $currentDate. I tried it with the above example but it still gives out all the events on the database. It needs to be passed as multiple $events (array) as I need to access it in a seperate blade and do the templating in there.

Here is how a blade would look like:

<div class="text-2xl">{{ $event->coursname }}</div>
<div>{{ $event->start }}, {{ $event->end }}</div>

So I already have the info about the start and can compare it to the $currentDate but for some reason this wont work.

CodePudding user response:

If you only need the events that haven't started yet, it's going to be a better idea to add a where clause to your query rather than getting all of them and filtering them down in code:

$events = DB::table('eventaries')
    ->where('category', $id)
    ->where('start', '>', now())
    ->get();

CodePudding user response:

You have two "culprits":

1.

// get the course data from the database
$events = DB::table('eventaries')->where('category', $id)->get();
foreach ($events as $event) {
    if ($event->start > $currentDate) {
        return view($view, [
            "events" => $events,
        ]);
    }
}

In the query (1) you get all the events, in the foreach (2) you are comparing the start date for each events on the DB, if you find at least one that is already started, you return the view with all the $events.

Simple solution: remove the foreach and the if and just return you view. Use your query to filter out the started events with something like this:

$events = DB::table('eventaries')->where('category', $id)->where('start', '>', $currentDate)->get();

Addendum: since you are using laravel, you could use your model instead of DB facade, like:

Eventaries::whereCategory($id)->where('start', '>', $startDate)->get();
  • Related