Problem
I am trying to build a simple REST API and just starting. Want to print back the JSON format, however, I am getting the following error:
FatalErrorException in ProjectsController.php line 74:
Call to undefined method Illuminate\Http\Response::json()
Call to undefined method Illuminate\Http\Response::json()
Where is the Response::json()
is located? What am I doing wrong?
Solution
What you want to do is use the helper method really because it simply works without needing to use namespace.
return response()->json(['name' => 'Laravel Recipes', 'state' => 'NY']);
This will create an instance of \Illuminate\Routing\ResponseFactory. You can check the method to see what arguments you can use:
/**
* Return a new JSON response from the application.
*
* @param string|array $data
* @param int $status
* @param array $headers
* @param int $options
* @return \Symfony\Component\HttpFoundation\Response
* @static
*/
public static function json($data = array(), $status = 200, $headers = array(), $options = 0){
return \Illuminate\Routing\ResponseFactory::json($data, $status, $headers, $options);
}
* Return a new JSON response from the application.
*
* @param string|array $data
* @param int $status
* @param array $headers
* @param int $options
* @return \Symfony\Component\HttpFoundation\Response
* @static
*/
public static function json($data = array(), $status = 200, $headers = array(), $options = 0){
return \Illuminate\Routing\ResponseFactory::json($data, $status, $headers, $options);
}