Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Modify json output in laravel

I want to remove some element from my json output
My Output is :

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

I want simple output, like this :

[
  {
    "_id": "6580f69587f0f77a14091c22",
    "email": "janzboy@gmail.com",
    "first_name": "Janz",
    "last_name": "Boy",
    "password": "1995",
  }
]

Here’s my controller :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Do me your biggest favor brother..

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading