18

I am trying to response a json with the json array in Laravel5

namespace App\Http\Controllers;
use Illuminate\Routing\ResponseFactory;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\Event;

class EventsapiController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        //
        $events =  Event::All();

        return Response::json([

                'data'=>$events

        ],200);

    }
}

Its giving me this error

Call to undefined method Illuminate\Http\Response::json() in Laravel5

So how do we pass json in Laravel 5 ? , I Already know laravel returns automatically json array but I don't want to do that

Thanks

3 Answers 3

19

Try the helper function:

return response()->json(['data'=>$events]);

See the docs in \Illuminate\Routing\ResponseFactory:

/**
 * Return a new JSON response from the application.
 *
 * @param  string|array  $data
 * @param  int  $status
 * @param  array  $headers
 * @param  int  $options
 * @return \Illuminate\Http\JsonResponse
 */

public function json($data = [], $status = 200, array $headers = [], $options = 0)
{
    if ($data instanceof Arrayable && ! $data instanceof JsonSerializable) {
        $data = $data->toArray();
    }
    return new JsonResponse($data, $status, $headers, $options);
}
Sign up to request clarification or add additional context in comments.

1 Comment

Oh got it the syntax has changed from 4.1 :)
19

You are using:

Illuminate\Http\Response

and should use this instead:

\Response

Type:

use Response;

Don't type:

use Illuminate\Http\Response;

Comments

0

If you return data, you simply return an array from your controller method, it will render as JSON. You can return

return [
        'status' => true
        'data' => events
    ];

Or Use Helper Function:

return response()->json([''status' => true, data'=>$events]);

1 Comment

As OP stated in his question, he "Already know laravel returns automatically json array but I don't want to do that".

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.