3

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();
    }
}

1 Answer 1

1
$query // your query

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

$sortedQuery = $query->get();
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.