Search code examples
phplaravel-5eloquentsql-order-by

Pass an array of ORDER BY values to Eloquent orderBy() method


I have code to manipulate an array like this:

$args['orderby'] = array('id', 'asc');
$orderby = (string) str_replace(
    '"',
    "'",
    str_replace(
        ']',
        '',
        str_replace(
            '[',
            '',
            json_encode($args['orderby'])
        )
    )
);
//Result $orderby = "'id','asc'";

I pass the variable $orderby to Laravel's orderBy() method, but it is not work for me.

Table::select($args['value'])
->where($coloumn_search, 'ilike', '%' . $search . '%')
->orderBy($orderby)
->get();

If I hardcode 'id','asc' into the orderBy() method, it works.

Table::select($args['value'])
->where($coloumn_search, 'ilike', '%'.$search.'%')
->orderBy('id','asc')
->get();

What is the difference between 'id','asc' and my generated variable?


Solution

  • These are two completely different things:

    • ->orderBy($orderby): one array parameter
    • ->orderBy('id','asc'): two string parameters

    You can use an array like this:

    ->orderBy(...$orderby)