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

garrettmassey's avatar

Using query scopes vs. methods on Eloquent models.

I am having trouble wrapping my head around this...

If I have an eloquent model called "Business" and each business can have a schedule, what I do to get the entire schedule is this:

$business = Business::find($id);
$schedule = $business->schedule;

The definition of schedule is in the BusinessController, like so:

	/**
     * gets the business's schedule
     *
     * @return \Illuminate\Database\Eloquent\Model
     */
    public function schedule() {
        return $this->hasMany('App\Models\Schedule');
    }

And the Schedule model's table is the business_schedule table, where it contains a row with the day of the week, the open time, and the close time.

What I am trying to do is something like this:

$monday = $business->schedule->weekDay(1);

and that would run the query that selects the item from the DB where the business_id matches, and the weekday = 1, that way if I only want to get a specific day of the week, I can just pass that day of the week into the weekDay() method.

Am I going about this the right way? Or am I overcomplicating this. I think i can do it with query scopes, but I'm not very familiar with them.

0 likes
2 replies
Sinnbeck's avatar
Sinnbeck
Best Answer
Level 102

You need to use the query builder by adding ()

$monday = $business->schedule()->where('wekday', 1)->get();
1 like
Elliot_putt's avatar

With query scopes, this should work it would be like so in the business model create a function called

scopeWeekDay($query ,$weekDay){
  $query->where('week_day_field_name','like','%' . $weekDay. '%')
}
1 like

Please or to participate in this conversation.