Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Three different methods in Laravel for if the request is asking for JSON. Are they the same? Do any overlap?

So these three methods are in the Laravel docs for testing if the request is for JSON.

I basically want to return JSON for any request that is requesting JSON or AJAX.

Request::ajax() Request::isJson() Request::wantsJson()

Can I use any of these? Do they overlap?

like image 500
Dr. Chocolate Avatar asked Jun 30 '17 21:06

Dr. Chocolate


1 Answers

Not all AJAX requests expect a JSON response, so utilizing request()->ajax() is useful where you want to determine if the request was an XmlHttpRequest or not, but the response doesn't care about JSON or not.

Not all requests that contain JSON expect a JSON response. so if you don't care about whether or not the response wants JSON back, but want to determine if JSON was sent in the request, then isJson() is useful for you.

Not all requests that want JSON responses are AJAX driven, so wantsJson is useful in the case where you want to return JSON data, but you don't care how the request came to your server.

Based on these descriptions, make assertions and choose the proper functions.

like image 92
Ohgodwhy Avatar answered Oct 05 '22 15:10

Ohgodwhy