php Request::all() 中未定义的方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34675057/
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-26 00:09:13  来源:igfitidea点击:

Undefined Method in Request::all()

phplaravellaravel-5

提问by Gerrit

I try the getting startedguide from Laravel.com.

我尝试了Laravel.com 上的入门指南。

There is a chapter Creating the task. There is $requesta parameter of the callback and in the function $request->all()is used to get the GET-Parameters. But if I execute that callback I get the error

有一章创建任务。有$request一个回调参数,在函数$request->all()中用于获取 GET 参数。但是如果我执行那个回调我会得到错误

Fatal error: Call to undefined method Illuminate\Support\Facades\Request::all()

致命错误:调用未定义的方法 Illuminate\Support\Facades\Request::all()

Here is my code:

这是我的代码:

Route::post('/task', function(Request $request) {

    $validator = Validator::make($request->all(), [
        'name' => 'required|max:255',
    ]);

    if($validator->fails())
        redirect('/')->withInput()->withErrors($validator);

    $task = new Task();
    $task->name = $request['name'];
    $task->save();

    return redirect('/');
});

回答by jedrzej.kurylo

Your controller function gets injected an instance of Illuminate\Support\Facades\Requestthat forwards only static calls to underlying requestobject.

您的控制器函数被注入一个Illuminate\Support\Facades\Request实例,该实例仅将静态调用转发到底层请求对象。

In order to fix that you need to import the underlying request class so that it is injected correctly. Add the following at the top of your routes.phpfile:

为了解决这个问题,您需要导入底层请求类,以便正确注入。在routes.php文件的顶部添加以下内容:

use Illuminate\Http\Request;

or just call Request::all()instead of $request->all().

或者只是调用Request::all()而不是$request->all()

回答by patricus

Since this code is in the routes.php file, which is not namespaced, the Requestobject being injected into your closure is the Requestfacade, not the Illuminate\Http\Requestobject. The Requestfacade does not have an all()method.

由于此代码位于没有命名空间的 routes.php 文件中,因此Request注入到您的闭包中RequestIlluminate\Http\Request对象是Facade,而不是对象。该Request门面没有一个all()方法。

Change your code to:

将您的代码更改为:

Route::post('/task', function(\Illuminate\Http\Request $request) {
    // code
});

Note: you generally don't fully qualify the Requestobject in Controller methods because Controllers usually add a use Illuminate\Http\Request;at the top. This is why your function definition in the routes file may look a little different than a controller method definition.

注意:您通常不会完全限定Request控制器方法中的对象,因为控制器通常use Illuminate\Http\Request;在顶部添加一个。这就是为什么路由文件中的函数定义可能与控制器方法定义略有不同的原因。

You can check out thisanswer for a little more information.

您可以查看答案以获取更多信息。