Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

kennybjr87's avatar

Multiple things to one query

Looking for some advice / proper way to handle doing multiple things to one query so, for example, lets say I have a table called Events on the dashboard I need to do two things I need to first count the total number of events so I can display that to my view but I also need to only display these events that are coming up not the past dates on the same controller. which would obviously be a where clause so without doing multiple queries for the same table how could I split this up? I have tried something like this.

    $events = Events::where('user_id', Auth::user()->id);

    //do whatever I need to here first as in count results

    //then my where to display only upcoming events nothing in the past
     $events->where('end_date', '>=', Carbon::today()->toDateString())->paginate(15);

but I get an appends error trying to display that to my view

0 likes
3 replies
petrit's avatar
...
$events->whereDate('end_date', '>=', date('Y-m-d'))->paginate(15);
...
realrandyallen's avatar
Level 44

You can do this with one query, or use a scope to clean things up a bit:

One query

// simply add on another where statement to your original query
$events = Events::where('user_id', Auth::user()->id)->where('end_date', '>=', now())->paginate(15);

Scope on Events Model

public function scopeUpcoming($query)
{
    return $query->where('user_id', Auth::user()->id)->where('end_date', '>=', now());
}

//usage in controller:
Events::upcoming()->paginate(15)

To display a count in your view simply:

// if paginated
{{ $events->total() }}

// if not paginated
{{ $events->count() }}
1 like

Please or to participate in this conversation.