Taras Chernata
Taras Chernata

Reputation: 401

Sort a result of search in Laravel Eloquent model with relations

I did a search for a Model (Startup), next step is to order results of the search by DESC or ASC (it doesn't matter now)

My current code is:

$startups = Startup::whereHas('category', function ($query) use ($search, $sort_type) {
            $query

                ->where('name', 'like', "%$search%")
                ->orderBy('name', $sort_type);
        })
            ->orWhere('description', 'LIKE', "%$search%")
            ->orWhere('url', 'LIKE', "%$search%")
            ->get();

        return StartupResource::collection($startups);

Explanation of the code: as you see at the beginning I'm using "whereHas" to search also for coincidences in related model - "Category". then inside of "whereHas" I'm trying to apply 'orderBy('name', $sort_type)' but it doesn't work properly (it doesn't sort by categories)

I know that we can create method in Startup model and sort it inside of the method, but the problem is that I have to pass variables to the method ( $sort_type, $search) and I don't know how to do this

So how to sort Startups model including related Category model by ASC or DESC in my case ?

Thank you guys a lot for any ideas and help!

Upvotes: 0

Views: 242

Answers (1)

Jonas Staudenmeir
Jonas Staudenmeir

Reputation: 25906

That's not possible with whereHas(). You can use a JOIN:

$startups = Startup::select('startups.*')
    ->join('category', 'category.id', '=', 'startups.category_id')
    ->where('category.name', 'LIKE', "%$search%")
    ->orWhere('startups.description', 'LIKE', "%$search%")
    ->orWhere('startups.url', 'LIKE', "%$search%")
    ->orderBy('category.name', $sort_type)
    ->get();

Upvotes: 1

Related Questions