0

I have implemented in my controller function $request->wantsJson() and there is content for my JSON output, how can I call json version?

Is there new route needed? Where can I set by call the type should be text/javascript?

My code example:

public function customersList(Request $request) {
    if ($request->wantsJson()) {

    return response()->json($result);
    }

    return view('customers/list');
}
rap-2-h
  • 30,204
  • 37
  • 167
  • 263
nowilius
  • 131
  • 1
  • 13
  • 1
    Possible duplicate of [How does Laravel know Request::wantsJson is a request for JSON?](http://stackoverflow.com/questions/26532060/how-does-laravel-know-requestwantsjson-is-a-request-for-json) – Jerodev Jan 26 '17 at 08:17
  • Yes, you must add new route, or you could you `$request->ajax()` and generate AJAX call from client-side. – Miron Jan 26 '17 at 08:18
  • @Miron ok. but what do I have to set in route, as header content type text/javascript? – nowilius Jan 26 '17 at 08:25
  • You can prefer http://stackoverflow.com/questions/18685321/how-to-make-laravel-return-a-views-content-type-header-as-application-javasc. Actually, it's not necessarily to use new route, but you can yet. – Miron Jan 26 '17 at 15:36

1 Answers1

1

You can test by sending Accept: application/json to your test request.

Exemple with curl:

$curl = curl_init();
curl_setopt_array($curl, [
    CURLOPT_URL => "http://example/my-route", 
    CURLOPT_HTTPHEADER => ["Accept" => "application/json"], 
    CURLOPT_RETURNTRANSFER => true
]);
curl_exec($curl);

More information here: https://stackoverflow.com/a/26532180/978690 (possible duplicate, not sure right now)

Community
  • 1
  • 1
rap-2-h
  • 30,204
  • 37
  • 167
  • 263