Laravel multiple orderBy from dynamic array input

17,679

Yes, you can add stuff to your query object after creating it like this:

<?php
$query = DB::table('advertisements');
foreach (Input::get('sort') as $key => $value) {
    $query->orderBy($key, $value);
}
$advertisements = $query->get();
Share:
17,679

Related videos on Youtube

Rafael
Author by

Rafael

https://rlc.ninja/

Updated on September 15, 2022

Comments

  • Rafael
    Rafael over 1 year

    I am trying to add orderBy clauses to a query dynamically.

    What I've tried

    $sort = Input::get('sort');
    
    // Ex. of $sort below  
    // Could be more or less key / values depending on user input
    "category" => "asc",
    "created_at" => "desc",
    "email" => "asc",
    "title" => "asc"
    
    // I need to chain multiple orderBy's to a query
    // but I can't use foreach in the laravel query
    foreach ($sort as $key => $value) {
      echo "->orderBy(\"$key\", \"$value\")";
    }
    

    Is there a way to chain multiple orderBy's to an existing query? Or a way to chain them during the creation of the query?

    I am using Bootgrid and trying to utilize it's multisort capabilities.

    Code update

    This is producing a status code 500.

    $advertisements = DB::table('advertisements')
                        ->get();
    
    foreach ($sort as $key => $value) {
        $advertisements->orderBy($key, $value);
    }
    
  • Rafael
    Rafael over 9 years
    Am I assigning the variable to the foreach?
  • mopo922
    mopo922 over 9 years
    @Rafael This just tacks on an extra orderBy() to your Laravel $query object for each sort value in your Input. I'm assuming you have instantiated a Laravel query builder object somewhere in your PHP, like $query = DB::table('table_name')->where('field', '=', 'etc')
  • mopo922
    mopo922 over 9 years
    @Rafael I see the problem from your update to your question. See how I've updated my answer - the ->get() has to go last.