How to return JSON data to the user in Laravel?

October 26, 2018

The correct way to do it in Laravel is returning response()->json(...) such as:

<?php
        return response()->json(['foo'=>'bar']);

If you need to return a JSONP response (with a callback function), then you can use ->withCallback($callback_function_name), such as:

<?php
return response()
            ->json(['name' => 'Abigail', 'state' => 'CA'])
            ->withCallback($request->input('callback'));