Skip to content
Advertisement

How to pass array as SELECT params for Laravel Query Builder

If I have an AJAX call that returns an array called $selectArray, which is [foo,bar,foobar], how do utilize it in a Laravel Query Builder so that it’s sanitized? Currently, I have

// Sanitizing Input
// $acceptableSelects is an array of columns in a table. Checks if there are any elements in $selectArray that is invalid
// If the check fails, it return the default array
$sanSelectArray = !array_diff($selectArray, array_keys($accetableSelects)) && count($selectArray) < 8 ? $selectArray : [foo,foo2,foo3]

foreach($sanSelectArray as $ele){
    $query->addSelect('table.' . $ele); // Required since I have a LEFT JOIN
}

It seems awfully unintuitive. Either there are better ways sanitizing the input or passing Array as SELECT without having multiple addSelect() methods, but I can’t find any.

Advertisement

Answer

You can pass an array to the addSelect() method. e.g.

$query->addSelect(['my', 'array', 'of', 'columns']);

Laravel query builder test

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement