How to return JSON data to the user in Laravel?

Laravel: How to return JSON data to the user in Laravel?

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

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

  1. return response()
  2.             ->json(['name' => 'Abigail', 'state' => 'CA'])
  3.             ->withCallback($request->input('callback'));

webdevetc profile pic
webdevetc

I am a 29 year old backend web developer from London, mostly focusing on PHP and Laravel lately. This (webdevetc.com) is my blog where I write about some web development topics (PHP, Laravel, Javascript, and some server stuff). contact me here.



More...


Comments and discussion about How to return JSON data to the user in Laravel?

Found this interesting? Maybe you want to read some more in this series?

Or see other topics in the Laravel language

Or see other languages/frameworks:
PHP Laravel Composer Apache CentOS and Linux Stuff WordPress General Webdev and Programming Stuff JavaScript
Or see random questions

How to hide directory listing in .htaccess?

How to force gzip compression in Apache with .htaccess

How to block IPv6 IP addresses in .htaccess

What is camel case?

How to block an IP range based on CIDR in Apache with .htaccess

How to return an item in Eloquent, or throw a ModelNotFoundException exception if it isn't found?

How can you check if a variable is alphanum (alphanumeric, letters and numbers only) in PHP?

How to get the first row that matches some where queries, or create it if it doesn't exist (in Laravel's Eloquent)?

How to set up an alias to map one directory to another destination

How to get a route to directly show a view?