i am creating a laravel project.i have get the data from database and viewing into json format as a Ascending order. i tried the example but not working.what i tried so far i attached below.
$keyword = $request->get('search');
$perPage = 25;
if (!empty($keyword)) {
$courses = Course::where('name', 'LIKE', "%$keyword%")
->all()->paginate($perPage);
} else {
$courses = Course::all()->paginate($perPage);
}
return response()->json($courses)->orderBy('id', 'asc')->get();
3
Answers
You cannot use orderBy in not Eloquent Class. Instead, use it on Eloquent Builder.
When an eloquent builder call all() is not eloquent anymore, it is become Collection.
Try this:
You can
orderBy
with the query, not after like the docs. Andall()
will return all results.Why do you sort afterwards? Why don’t you perform the sorting with the database engine before the query?
Here you’re telling Laravel to "convert it to JSON text", and then you want to tell the text to "sort by the ID column", but now we’re no longer talking about arrays and objects, but rather about text, so your request doesn’t make sense.
Solution
More concise, thoughtful coding
Summary
Build Query
Firstly, we need to assemble what we want to query. For this, we can use functions like
->where()
,->orderBy()
,->groupBy()
, etc. You can chain them together with any logic you need.Get Result
Once this logic is built, you can retrieve the records that match the conditions using the
->first()
,->get()
,->all()
, or->paginate()
functions. This will give you an object or an array, depending on the function used. (This is already good on its own.)all() or get()?
The
all()
method returns all query results as a collection, while theget()
method only returns the results as a simple array. Therefore, theall()
method cannot have any direct influence or filtering applied It can only filter the already retrieved records afterwards. This can often be problematic. Imagine a table with 10,000 rows, where you fetch all 10,000 rows and then filter out the ones with odd IDs, resulting in 5,000 records. In contrast, using pre-filtering with theget()
method, the database would have performed the filtering, and the server would only receive 5,000 records instead of the full 10,000.In my opinion, the
all()
method can be useful in very rare cases. Database engines are capable of performing filtering and grouping operations with excellent performance, makingget()
a very practical alternative. The all() method may provide some advantages when listing or exporting all data, but even in those cases, its usefulness is limited. Thepaginate()
method you used is a great way to avoid working with all records at once.It’s always important to make sure that whenever possible, we only query the necessary records and minimize the number of queries executed.
Send with response
After that, you can transform the array/object into JSON format using
->json()
if you want to transmit it to the client side.