MTA
MTA

Reputation: 1073

Laravel: Dynamic query sort by api

I am laravel newbie and am trying to write an search API, the example url is below. The sort '+' means ascending and '-' means descending. The query, category part is done and I am getting the desired results but sorting part is left. I don't know how to do multiple sorting dynamically. Can i give an array of sorting in orderBy like in where() clause [['rating','asc'], ['distance','desc']]. I have seen many posts, people do multiple sorting by calling orderBy() again and agin but that is static e.g orderBy('rating','asc')->orderBy('distance','desc'), How can i do that dynamically?

localhost:8000/search?q=query&cat=category&sort=+rating,-distance,-age

class SearchController extends Controller
{
    public function index(Request $request){

        $sort = explode(',', $request->sort);

        return DB::table('posts')->join('users', 'users.id', '=', 'posts.user_id')->join('locations', 'locations.id', '=', 'users.location_id')->join('main_categories', 'main_categories.id', '=', 'posts.main_category_id')->select('posts.*', 'users.*', 'locations.address', 'main_categories.name as cat', DB::raw('ROUND((6371 * ACOS(COS(RADIANS(31.430443800000003)) * COS(RADIANS(locations.lattitude)) * COS(RADIANS(locations.longitude) - RADIANS(74.280726)) + SIN(RADIANS(31.430443800000003)) * SIN(RADIANS(locations.lattitude)))),2) AS DISTANCE'))->where([['posts.title','like','%'.$request->q.'%'],['main_categories.name', '=', $request->cat]])->orwhere([['posts.description','like','%'.$request->q.'%'],['main_categories.name', '=', $request->cat]])->orderBy($request->sort,'DESC')->get();
    }
}

Upvotes: 3

Views: 3339

Answers (1)

Mortada Jafar
Mortada Jafar

Reputation: 3679

$query // your query

foreach($sorts as $sort)
{
  $query->orderBy($sort,'DESC')
}

$sortedQuery = $query->get();

Upvotes: 1

Related Questions