yiddishe-kop
yiddishe-kop

Reputation: 508

Laravel get next/previous record by specific column

I have a Product model.

I want to get the next previous Product, ordered by the name, NOT the id.

This is what I have now:

    public function getNextAttribute() {
        return FontFamily::select('id', 'name')->where('id', '>', $this->id)->orderBy('name', 'asc')->first() ?? FontFamily::first();
    }

    public function getPreviousAttribute() {
        return FontFamily::select('id', 'name')->where('id', '<', $this->id)->orderBy('name', 'desc')->first() ?? FontFamily::latest()->first();
    }

However using orderBy('name') doesn't do the trick, as I need to get tne next not based on the id but based on the name.

Appreciate any help!

Upvotes: 0

Views: 178

Answers (1)

gbalduzzi
gbalduzzi

Reputation: 10166

Your where condition should be on the name as well, not on the id:

    public function getNextAttribute() {
        return FontFamily::select('id', 'name')->where('name', '>', $this->name)->orderBy('name', 'asc')->first() ?? FontFamily::first();
    }

    public function getPreviousAttribute() {
        return FontFamily::select('id', 'name')->where('name', '<', $this->name)->orderBy('name', 'desc')->first() ?? FontFamily::latest()->first();
    }

Upvotes: 1

Related Questions