Search code examples
laravelphp-carbon

How to check date validation with Carbon in Laravel 8.*


I've got index page on which I'm displaying events.

@foreach($events as $event)
    <div class="row">
        <div class="d-flex justify-content-center" style="margin: auto">
            <a href="{!! route('eventView', ['id' => $event->id]) !!}" style="text-decoration: none;">

                <div class="row" style="margin-top: 10 px">
                    <p style="display:block">{{$event->name}}</p>
                </div>
                @if($event->photo_patch)
                <img src="{{ asset('storage/' . $event->photo_patch) }}">
                @else
                <img src="placeholder" alt="...">
                @endif
            </a>
        </div>
    </div>
    </div>
    @endforeach

But the problem is that its displaying all events, even those which took place in the past.

I would like to display events only with today's or future date

So I'm stuck now and I dont know what to do next.

I tried to do loop which shows me events that are today/in the future:

public function index()
    {
        $date = Carbon::today();
        $events = Event::where('date_of_event' >= $date)->get();

        foreach($events as $event){
            if($event->date_of_event >= $date){
                dump('Valid');
            }
            else{
                dump('Invalid');
            }
        }

        dump($events);
        dump($date);
        return view('frontend/index',['events'=>$events]);
    }

But I dont know how to display them later inside of my view.

My second shot was to do it with this line:

$events = Event::where('date_of_event' >= $date)->get();

But then I've got error :

SQLSTATE[42S22]: Column not found: 1054 Unknown column '1' in 'where clause' (SQL: select * from `events` where `1` is null)

which isnt really accurate since column name should be valid.

How can I implement that properly?


Solution

  • The default operator for where is =. If you want to change this you'll use the second argument for the operator and the third for your value.

    Event::where('date_of_event', '>=', $date)->get();
    

    See Where Clauses for more details.