I'm trying to order my result set using eloquent builder but it is not working. I tried investigating this unfortunate phenomena but I only learnt that according to the api documentation accessible : here
The eloquent builder class does not have orderBy() method. Am I wrong to say Eloquent Builder is a wrapper for Query Builder? If so, why is orderBy() method missing from Eloquent Builder class but does not throw call to undefined method error when used and why is it not working as expected? To access orderBy('sortColumn') method, I call getQuery() on the Eloquent\Builder instance which returns an instance of Query\Builder.
use Illuminate\Support\Str;
use Illuminate\Http\Request;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Collection as EloquentCollection;
private static function getResults(Builder $builder): EloquentCollection {
/* return new EloquentCollection($builder?->getQuery()->orderBy(request()?->filled('sortColumn')
? request('sortColumn')
: 'movieTitle')?->get()); */
return $builder?->when(request()?->filled('sortColumn'), function ($builder) {
return $builder
?->getQuery()
?->orderBy(Str::squish(request('sortColumn')));
}, fn ($builder) => $builder)?->get();
}
The code above throws the exception below when sorting is applied, but works fine if sorting is not applied.
Error: Return value must be of type Illuminate\Database\Eloquent\Collection, Illuminate\Support\Collection returned.
I tried again to convert the Support\Collection back to Eloquent\Collection using commented code in the code sample above, but this too, threw an exception below when I attempted to paginate the result set using the code below:
Error: Call to undefined method stdClass::newModelQuery()
$resultSet?->toQuery()?->paginate(8);
I cannot directly paginate Eloquent\Collection, so I call toQuery() method to access the Eloquent query builder from the collection and use it to access the paginate(8) method.
I would greatly appreciate any help you can afford me in getting the Eloquent\Builder to sort data using orderBy('sortColumn') method and return an Eloquent\Collection that can be paginated.