Ad

Conditional OrderBy

I'm building a filter function in a project.

I have a filter option "Show newest", "Show oldest" and a bunch of other options. I found a way how to implement conditional where clauses, but there doesn't seems to be a conditional orderBy class.

My conditional where clause looks like this:

$query->where(function($query) use ($request){
   if( ! empty($request->input('prices')) ){
      $opts = $request->prices;
      $query->where('price_id', $opts[0]);
   }
})

Is there a way to do this with a ->orderBy too?

UPDATE

return Auction::where('end_date', '>', Carbon::now() )
         ->where('locale', $locale)
         ->where('sold', 0)
         ->where(function($query) use ($request){

             if( ! empty($request->input('prices')) ){
                  $opts = $request->prices;
                  $query->where('price_id', $opts[0]);
             }
         })->paginate(8);

How can I do it in the eloquent-way?

Ad

Answer

Of course, you can do it this way:

if ($request->input('id_desc')) {
   $query = $query->orderBy('id', 'DESC');
}

or you can do it this way:

$columns = ['id','name',]; // here define columns you allow for sorting
$orderBy = ['ASC', DESC'];


$column = $request->input('order_by_column');
$type = $request->input('order_by_type');

if (!in_array($column, $columns)) {
  $column = 'id';
}
if (!in_array($type , $orderBy )) {
  $type = 'ASC';
}

$query = $query->orderBy($column, $type);

EDIT

Using your code:

$query = Auction::where('end_date', '>', Carbon::now() )
         ->where('locale', $locale)
         ->where('sold', 0)
         ->where(function($query) use ($request){

             if( ! empty($request->input('prices')) ){
                  $opts = $request->prices;
                  $query->where('price_id', $opts[0]);
             }
         });


if ($request->input('id_desc')) {
    $query = $query->orderBy('id', 'DESC');
}

return $query->paginate(8);
Ad
source: stackoverflow.com
Ad