skip to Main Content

I want to remove some elements from my JSON output.

My Output is:

[
    {
        "current_page": 1,
        "data": [
            {
                "_id": "6580f69587f0f77a14091c22",
                "email": "[email protected]",
                "first_name": "Janz",
                "last_name": "Boy",
                "password": "1995",
            }
        ],
        "first_page_url": "http://localhost:8000/api/customer?page=1"
    }
]

I want a simple output like this:

[
  {
    "_id": "6580f69587f0f77a14091c22",
    "email": "[email protected]",
    "first_name": "Janz",
    "last_name": "Boy",
    "password": "1995",
  }
]

Here’s my controller:

class CustomerController extends Controller
{
    public function index()
    {
        $customers=Customer::paginate(10);
        return response()->json([
            'data'=> $customers 
        ]);
    }
}

Do me your biggest favor, brother.

2

Answers


  1. To modify the JSON output how you want, you should change the data you send in the response. Instead of sending the whole paginated object, you should only send the data part of it.

    class CustomerController extends Controller
    {
        public function index()
        {
            $customers = Customer::paginate(10);
            return response()->json($customers->items());
        }
    }
    

    In this code, $customers->items() will return an array of the current page items, giving you the desired output.

    Login or Signup to reply.
  2. To achieve the desired output without the pagination information, you can modify the code to return just the array of customers without using pagination:

     class CustomerController extends Controller
    {
        public function index()
        {
            $customers = Customer::all(); // Retrieve all customers
            return response()->json($customers);
        }
    }
    

    This modification fetches all customers without pagination and directly returns the array of customer objects in the JSON response. However, keep in mind that using Customer::all() can be inefficient for large datasets since it retrieves all records at once. Pagination is typically used to handle large data sets more efficiently by breaking them into smaller chunks. If you have a large number of customers, it might be better to stick with pagination and refine the output format on the client-side to fit your desired structure.

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