【问题标题】:Call to undefined method Illuminate\Http\Response::json() in Laravel5在 Laravel5 中调用未定义的方法 Illuminate\Http\Response::json()
【发布时间】:2016-03-14 17:13:45
【问题描述】:

我正在尝试用 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);

    }
}

它给了我这个错误

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

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

谢谢

【问题讨论】:

    标签: php json laravel-5.1


    【解决方案1】:

    试试helper function

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

    查看\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);
    }
    

    【讨论】:

    • 哦,知道了,语法已经从 4.1 改变了 :)
    【解决方案2】:

    您正在使用:

    照亮\Http\响应

    应该改用这个:

    \响应

    类型:

    use Response;
    

    不要输入:

    use Illuminate\Http\Response;
    

    【讨论】:

      【解决方案3】:

      如果您返回数据,您只需从控制器方法返回一个数组,它将呈现为 JSON。你可以返回

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

      或使用辅助函数:

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

      【讨论】:

      • 正如 OP 在他的问题中所说,他“已经知道 laravel 会自动返回 json 数组,但我不想那样做”。
      猜你喜欢
      • 1970-01-01
      • 2016-11-18
      • 1970-01-01
      • 2018-07-04
      • 2015-09-23
      • 2018-10-02
      • 2023-03-23
      • 2020-04-07
      • 2020-03-16
      相关资源
      最近更新 更多