Search code examples
phplaravellaravel-5laravel-5.3

Laravel call json version from controller?


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');
}

Solution

  • 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)