I want to add to a Laravel query using a callable.
For example, I have a string for sorting records. Based on this string, I want to add to my query via an array:
public $sort = 'Newest';
public function sortQuery(Builder $query)
{
return [
'Name' => $query->orderBy('name'),
'Newest' => $query->orderBy('created_at'),
'Oldest' => $query->orderByDesc('created_at'),
];
}
public function paginateQuery()
{
$query = User::query();
foreach ($this->sortQuery($query) as $key => $value) {
if ($this->sort == $key) {
$query = $value;
}
}
return $query->paginate();
}
In this example, when I run $this->paginateQuery()
it does not sort as desired.
I've also tried $query = $this->sortQuery($query)[$this->sort];
instead of the foreach
loop and the result is the same.
How would I chain $value
onto the $query
based on the array key?
My Answer:
> function ($query) {
$query->orderBy('name', 'asc');
},
'Newest' => function ($query) {
$query->orderBy('created_at', 'desc');
},
'Oldest' => function ($query) {
$query->orderBy('created_at', 'asc');
},
][$this->sort]($query);
}
This code snippet defines a `sortQuery` method that takes a `Builder` instance as a parameter and uses a callable array to determine how to sort the query based on the value of the `$sort` property. The `sortQuery` method then calls the appropriate callable function based on the value of `$sort` to add the necessary sorting logic to the query.
Rate this post
3 of 5 based on 4956 votesComments