skip to Main Content

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


  1. 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:

    $perPage = 25;
    $courses = Course::query();
    if ($request->has('search')) {
       $courses->where('name', 'LIKE', "%" . $request->get('search') . "%");      
    }
    $courses->orderBy('id', 'asc');
    $paginatedCourses = $courses->paginate($perPage);
    return response()->json($paginatedCourses);
    
    Login or Signup to reply.
  2. You can orderBy with the query, not after like the docs. And all() will return all results.

    $keyword = $request->get('search');
    $perPage = 25;
    
    $query = Course::query();
    
    if (!empty($keyword)) {
        $query->where('name', 'LIKE', "%$keyword%");
    }
    
    $courses = $query->orderBy('id', 'asc')->paginate($perPage);
    
    return response()->json($courses);
    
    Login or Signup to reply.
  3. 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.

    response()->json($courses)->orderBy('id', 'asc')->get()
    

    Solution

    $keyword = $request->get('search');
    $perPage = 25;
    
    if (!empty($keyword)) {
        $courses = Course::where('name', 'LIKE', "%$keyword%")
            ->orderBy('id', 'asc')
            ->paginate($perPage); // don't need ->all()
    } else {
        $courses = Course::orderBy('id', 'asc')
            ->paginate($perPage); // don't need ->all()
    
    }
    
    return response()->json($courses); // don't need ->get()
    

    More concise, thoughtful coding

    $keyword = $request->get('search');
    $perPage = 25;
    
    // It's a query that hasn't been executed yet
    // We're just building it to specify what we want. The query will be executed when one of the following functions is called: ->first(), ->get(), ->all(), or ->paginate()
    $courses = Course::orderBy('id', 'asc');
    
    if (!empty($keyword)) {
        // The query has still not been executed; we have just added a condition to it
        $courses = $courses->where('name', 'LIKE', "%$keyword%");
    }
    
    // The query was executed here using ->paginate(), and then we returned the response using response()->json()
    return response()->json($courses->paginate($perPage));
    

    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 the get() method only returns the results as a simple array. Therefore, the all() 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 the get() 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, making get() 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. The paginate() 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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search