Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

randm's avatar
Level 6

Is it possible to use API Resource to return JSONP?

I am trying to use jquery.ui autocomplete https://jqueryui.com/autocomplete/#remote in my Laravel 5.7 project.

It seems that the jquery.ui.autocomplete package expect jsonp not standard json. I have been creating a new ApiResource for all of my resources, so I would like to also use Api Resource to response to the autocomplete request.

How can I change the response type from json to jsonp when using Api Resources?

Here is home my controller looks like

class DriversController extends Controller
{
    /**
     * Display the specified reservation.
     *
     * @param int $vehicleId
     *
     * @return App\Resources\VehicleResources
     */
    public function find($term)
    {
        $topics = Topic::where('fullname', 'like', $term. '%')->get();

        return new TopicResource($topics);
    }
}

Here is my ApiResponse class

class TopicResource extends Resource
{
    /**
     * Transform the resource into an array.
     *
     * @param  \Illuminate\Http\Request $request
     * @return array
     */
    public function toArray($request)
    {
        return [
            // return something cool
        ];
    }

    /**
     * Returns other attributes to the request
     *
     * @param  \Illuminate\Http\Request $request
     *
     * @return array
     */
    public function with($request)
    {
        return [
            'status' => 'success',
        ];
    }
}
0 likes
2 replies
randm's avatar
randm
OP
Best Answer
Level 6

I added the following method to my TopicResouce class and the problem was fixed

    /**
     * Customize the response for a request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Illuminate\Http\JsonResponse  $response
     * @return void
     */
    public function withResponse($request, $response)
    {
        $response->withCallback($request->input('callback'));
    }
igaster's avatar

You can access the response by chaining ->response() to the resource:

return TopicResource::collect($topics)
  ->response()
  ->withCallback(...);

Please or to participate in this conversation.