lemonid
lemonid

Reputation: 107

How to custom OrderBy in Laravel

I wanted to do a custom ordering for marketing_status_id in this:

$prospect = $this->filterProspect($request->all())
            ->select([
                'student_marketings.*',
                'students.name',
                'students.identification_type_id',
            ])
            ->distinct('student_marketings.id')
            ->orderBy('student_marketings.marketing_status_id');

How to order it in this sequence: ('marketing_status_id', 5, 20, 4, 1, 3, 18, 6) ?

Upvotes: 2

Views: 2216

Answers (1)

TsaiKoga
TsaiKoga

Reputation: 13394

Use mysql inbuilt-method field() like this:

$prospect = $this->filterProspect($request->all())
            ->select([
                'student_marketings.*',
                'students.name',
                'students.identification_type_id',
            ])
            ->distinct('student_marketings.id')
            ->orderBy(DB::raw('FIELD(marketing_status_id, 5, 20, 4, 1, 3, 18, 6)'));

Upvotes: 5

Related Questions