php 调用 Laravel5 中未定义的方法 Illuminate\Http\Response::json()

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34178670/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 23:48:19  来源:igfitidea点击:

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

phpjsonlaravel-5.1

提问by Vikram Anand Bhushan

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

我正在尝试使用 Laravel5 中的 json 数组来响应 json

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

那么我们如何在 Laravel 5 中传递 json 呢?,我已经知道 laravel 会自动返回 json 数组,但我不想这样做

Thanks

谢谢

采纳答案by Peter Kota

Try the helper function:

尝试辅助功能

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

See the docs in \Illuminate\Routing\ResponseFactory:

请参阅\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);
}

回答by Paulo

You are using:

您正在使用:

Illuminate\Http\Response

照亮\Http\响应

and should use this instead:

并且应该使用它:

\Response

\回复

Type:

类型:

use Response;

Don't type:

不要输入:

use Illuminate\Http\Response;