Question

I am just looking for a cleaner alternative to this, and I couldn't find anything online.

Timetable::where('weekday', '0')->update(['times' => $weekdays[0]]);
Timetable::where('weekday', '1')->update(['times' => $weekdays[1]]);
Timetable::where('weekday', '2')->update(['times' => $weekdays[2]]);
Timetable::where('weekday', '3')->update(['times' => $weekdays[3]]);
Timetable::where('weekday', '4')->update(['times' => $weekdays[4]]);
Timetable::where('weekday', '5')->update(['times' => $weekdays[5]]);
Timetable::where('weekday', '6')->update(['times' => $weekdays[6]]);
Was it helpful?

Solution

You can put it in a simple for loop, but that doesn't make the code much cleaner (just shorter). Have a look at Eloquent's scope functionality. You could make it something like this:

class Timetable extends Eloquent {

    public function scopeWeekday($query, $day)
    {
        $query->where('weekday', $day);
    }

    public function updateTimes($weekday)
    {
        $data = array('times' => $this->weekdays[$weekday]);
        $this->update($data);
    }
}

I don't know what kind of data is in $weekdays, but you would use this scope and update method like this:

Timetable::weekday(1)->updateTimes(1);

I do realize this isn't shorter, but it surely is cleaner and much more readable. You could even combine the scope with the update, but I hope this inspires you to clean up the code.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top