Home » Php » php – Response::json() – Laravel 5.1

php – Response::json() – Laravel 5.1

Posted by: admin April 23, 2020 Leave a comment

Questions:

I am trying to return Response::json('data', $request); however, I am getting an error:

FatalErrorException in ProjectsController.php line 74:
Call to undefined method Illuminate\Http\Response::json()

Where is the Response::json() is located? What am I doing wrong?

How to&Answers:

use the helper function in laravel 5.1 instead:

return response()->json(['name' => 'Abigail', 'state' => 'CA']);

This will create an instance of \Illuminate\Routing\ResponseFactory. See the phpDocs for possible parameters below:

/**
* 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);
}

Answer:

After enough googling I found the answer from controller you need only a backslash like return \Response::json(['success' => 'hi, atiq']); . Or you can just return the array return array('success' => 'hi, atiq'); which will be rendered as json in Laravel version 5.2 .

Answer:

You need to add use Response; facade in header at your file.

Only then you can successfully retrieve your data with

return Response::json($data);

Answer:

From a controller you can also return an Object/Array and it will be sent as a JSON response (including the correct HTTP headers).

public function show($id)
{
    return Customer::find($id);
}

Answer:

although Response::json() is not getting popular of recent, that does not stop you and Me from using it.
In fact you don’t need any facade to use it,

instead of:

$response = Response::json($messages, 200);

Use this:

$response = \Response::json($messages, 200);

with the slash, you are sure good to go.

Answer:

However, the previous answer could still be confusing for some programmers. Most especially beginners who are most probably using an older book or tutorial.
Or perhaps you still feel the facade is needed. Sure you can use it.
Me for one I still love to use the facade, this is because some times while building my api I forget to use the ‘\’ before the Response.

if you are like me,
simply add

   "use Response;"

above your class …extends contoller.
this should do.

with this you can now use:

$response = Response::json($posts, 200);

instead of:

$response = \Response::json($posts, 200);