Laravel multiple orderBy from dynamic array input

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

What i 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 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 associate multiple orderBy with an existing request? Or a way to link them during query creation?

I am using Bootgrid and trying to use its multi-user capabilities.

Code update

This creates a status code of 500.

$advertisements = DB::table('advertisements')
                    ->get();

foreach ($sort as $key => $value) {
    $advertisements->orderBy($key, $value);
}
+4
source share
1 answer

Yes, you can add material to your request object after creating it as follows:

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

All Articles