【问题标题】:Getting an error in Laravel with response()使用 response() 在 Laravel 中获取错误
【发布时间】:2019-12-27 21:11:23
【问题描述】:

我是 PHP 和 Laravel 的新手,我一直在编写教程。我正在尝试将 json 传递到不同的路线,但我收到一条错误消息

BadMethodCallException
Call to undefined method Illuminate\Http\RedirectResponse::response()

在我的路线上,我有

Route::get('/nuevo','temm@changeView')
->name('tron');


Route::post('/postaedd','temm@fetchAndDis')
->name('postInfoo');


Route::post('/postedd12321',"temm@pazze")
->name('pazze');

在我的控制器上我有


    public function pazze(){
        return view('pass');
    }

     public function fetchAndDis(\Illuminate\Http\Request $request){

        $this->validate($request, [
            'email' => "required|min:5",
            "name" => "required|min:1"
        ]);

        $email = $request->input('email');
        $name = $request->input("name");

        $info=[
            'email' => $email,
            "name" => $name
        ];

        return 

        redirect()
        ->route('pazze')
        ->with('info', $info)
        ->response()
        ->json($info, 200);
    }

提交表单后出现错误

【问题讨论】:

  • redirect 将返回 301,而不是 json 正文,如果您想返回该 json,您应该只使用 return response(json_encode($info), 200) 或只使用 return json_encode($info),如果不是,请说明您想要实现的目标
  • 我正在尝试在新页面上传递 $info,如果成功,我将获得 200
  • 在这种情况下,尝试使用我给你的代码
  • 但是如何将 $info 传递给我的 pazze 路线?

标签: php laravel controller routing


【解决方案1】:

我不确定为什么需要 JSON,但您可以将数据闪存到会话,然后您可以检查会话是否在另一条路由上有变量。您的fetchAndDis 方法可以返回重定向,并将数据闪现到会话:

return redirect()->route('pazze')->with('info', $info);

然后在pazze 方法中你可以得到闪现的会话数据:

$info = $request->session()->get('info');

然后您可以检查使用或不使用会话数据做什么。

Laravel 6.x Docs - Responses - Redirects - Redirecting with Flashed Session Datawith

Laravel 6.x Docs - Sessions - Using the Session - Retrieving Dataget

【讨论】:

  • 当我尝试按照您所说的进行退货时,我又遇到了一个错误。 Symfony \ Component \ HttpKernel \ Exception \ MethodNotAllowedHttpException The GET method is not supported for this route. Supported methods: POST.
  • 如果你想重定向到它,它需要是一个GET 路由
  • 有没有办法在不使用 GET 路由的情况下做到这一点?或者什么是最佳编程实践?
猜你喜欢
  • 1970-01-01
  • 2020-11-29
  • 2018-08-03
  • 1970-01-01
  • 2016-08-27
  • 2016-04-24
  • 1970-01-01
  • 2020-04-04
  • 1970-01-01
相关资源
最近更新 更多