Laravel Request :: all ()은 정적으로 호출하면 안됩니다.
Laravel 에서 컨트롤러 $input = Request::all();
의 store()
메서드 를 호출하려고 하는데 다음과 같은 오류가 발생합니다.
비 정적 메서드
Illuminate\Http\Request::all()
는$this
호환되지 않는 컨텍스트에서 가정 하여 정적으로 호출해서는 안됩니다.
이 문제를 해결하는 가장 좋은 방법을 찾는 데 도움이 있습니까? (나는 Laracast를 따르고 있습니다)
오류 메시지는 Request
외관을 통과하지 않는 호출 때문 입니다.
변화
use Illuminate\Http\Request;
에
use Request;
작동을 시작해야합니다.
config / app.php 파일에서 클래스 별칭 목록을 찾을 수 있습니다. 여기에서 기본 클래스 Request
가 클래스 에 별칭이 지정되었음을 알 수 Illuminate\Support\Facades\Request
있습니다. 이 때문에 Request
네임 스페이스 파일에서 파사드를 사용하려면 기본 클래스를 사용하도록 지정해야합니다 use Request;
..
편집하다
이 질문에 약간의 트래픽이 발생하는 것 같기 때문에 Laravel 5가 공식적으로 출시 된 이후로 답변을 조금 업데이트하고 싶었습니다.
위의 내용은 여전히 기술적으로 정확하고 작동하지만,이 use Illuminate\Http\Request;
문은 새로운 컨트롤러 템플릿에 포함되어있어 개발자가 Facade에 의존하는 대신 종속성 주입을 사용하는 방향으로 밀어 붙일 수 있습니다.
Request 객체를 생성자 (또는 Laravel 5에서 사용할 수있는 메서드)에 Illuminate\Http\Request
주입 할 때 주입해야하는 것은 Request
파사드가 아닌 객체입니다 .
따라서 Request 파사드와 함께 작동하도록 Controller 템플릿을 변경하는 대신 주어진 Controller 템플릿으로 작업하고 (생성자 또는 메서드를 통해) 종속성 주입을 사용하는쪽으로 이동하는 것이 좋습니다.
방법을 통한 예
<?php namespace App\Http\Controllers;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
class UserController extends Controller {
/**
* Store a newly created resource in storage.
*
* @param Illuminate\Http\Request $request
* @return Response
*/
public function store(Request $request) {
$name = $request->input('name');
}
}
생성자를 통한 예
<?php namespace App\Http\Controllers;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
class UserController extends Controller {
protected $request;
public function __construct(Request $request) {
$this->request = $request;
}
/**
* Store a newly created resource in storage.
*
* @return Response
*/
public function store() {
$name = $this->request->input('name');
}
}
Laravel의 매직 주입을 사용하여 컨트롤러에 요청 객체를 주입 한 다음 비 정적으로 함수에 액세스합니다. Laravel은 자동로드 된 클래스에 구체적인 종속성을 자동으로 주입합니다.
class MyController()
{
protected $request;
public function __construct(\Illuminate\Http\Request $request)
{
$this->request = $request;
}
public function myFunc()
{
$input = $this->request->all();
}
}
request()
대신 도우미를 사용하십시오 . use
진술 에 대해 걱정할 필요가 없으므로 이러한 종류의 문제가 다시 발생하지 않습니다.
$input = request()->all();
단순한
파사드는 또 다른 요청 클래스이며 전체 경로로 액세스합니다.
$input = \Request::all();
laravel 5에서는 다음 request()
함수를 통해 액세스 할 수도 있습니다 .
$input = request()->all();
use Illuminate\Http\Request;
public function store(Request $request){
dd($request->all());
}
문맥 상 동일하다
use Request;
public function store(){
dd(Request::all());
}
나는 미래의 방문객이 여기서 무슨 일이 일어나고 있는지에 대한 약간의 설명을 제공하는 것이 유용 할 것이라고 생각했습니다.
Illuminate\Http\Request
클래스
Laravel's Illuminate\Http\Request
class has a method named all
(in fact the all
method is defined in a trait that the Request
class uses, called Illuminate\Http\Concerns\InteractsWithInput
). The signature of the all
method at the time of writing looks like this:
public function all($keys = null)
This method is not defined as static
and so when you try to call the method in a static context, i.e. Illuminate\Http\Request::all()
you will get the error displayed in OP's question. The all
method is an instance method and deals with information that is present in an instance of the Request
class, so calling it in this way makes no sense.
Facades
A facade in Laravel provides developers with a convenient way of accessing objects in the IoC container, and calling methods on those objects. A developer can call a method "statically" on a facade like Request::all()
, but the actual method call on the real Illuminate\Http\Request
object is not static.
A facade works like a proxy - it refers to an object in the IoC container and passes the static method call onto that object (non-statically). For instance, take the Illuminate\Support\Facades\Request
facade, this is what it looks like:
class Request extends Facade
{
protected static function getFacadeAccessor()
{
return 'request';
}
}
Under the hood, the base Illuminate\Support\Facades\Facade
class uses some PHP magic, namely the __callStatic
method to:
- Listen for a static method call, in this case
all
with no parameters - Grab the underlying object from the IoC container using the key returned by
getFacadeAccessor
, in this case aIlluminate\Http\Request
object - Dynamically call the method that it received statically on the object it has retrieved, in this case
all
is called non-statically on an instance ofIlluminate\Http\Request
.
This is why, as @patricus pointed out in his answer above, by changing the use
/import statement to refer to the facade, the error is no longer there, because as far as PHP is concerned, all
has been correctly called on an instance of Illuminate\Http\Request
.
Aliasing
Aliasing is another feature that Laravel provides for convenience. It works by effectively creating alias classes that point to facades in the root namespace. If you take a look at your config/app.php
file, under the aliases
key, you will find a long list of mappings of strings to facade classes. For example:
'aliases' => [
'App' => Illuminate\Support\Facades\App::class,
'Artisan' => Illuminate\Support\Facades\Artisan::class,
'Auth' => Illuminate\Support\Facades\Auth::class,
// ...
'Request' => Illuminate\Support\Facades\Request::class,
Laravel creates these alias classes for you, based on your configuration and this allows you to utilise classes available in the root namespace (as referred to by the string keys of the aliases
config) as if you're using the facade itself:
use Request:
class YourController extends Controller
{
public function yourMethod()
{
$input = Request::all();
// ...
}
}
A note on dependency injection
While facades and aliasing are still provided in Laravel, it is possible and usually encouraged to go down the dependency injection route. For example, using constructor injection to achieve the same result:
use Illuminate\Http\Request;
class YourController extends Controller
{
protected $request;
public function __construct(Request $request)
{
$this->request = $request;
}
public function yourMethod()
{
$input = $this->request->all();
// ...
}
}
There are a number of benefits to this approach but in my personal opinion the greatest pro for dependency injection is that it makes your code way easier to test. By declaring the dependencies of your classes as constructor or method arguments, it becomes very easy to mock out those dependencies and unit test your class in isolation.
I was facing this problem even with use Illuminate\Http\Request;
line at the top of my controller. Kept pulling my hair till I realized that I was doing $request::ip()
instead of $request->ip()
. Can happen to you if you didn't sleep all night and are looking at the code at 6am with half-opened eyes.
Hope this helps someone down the road.
i make it work with a scope definition
public function pagar(\Illuminate\Http\Request $request) { //
참고URL : https://stackoverflow.com/questions/28573860/laravel-requestall-should-not-be-called-statically
'Nice programing' 카테고리의 다른 글
포인터를 정수로 변환 (0) | 2020.10.15 |
---|---|
glxgears에 대한 수직 동기화 비활성화 (0) | 2020.10.15 |
전체 서브넷에 대해 MySQL에 대한 원격 액세스 권한을 부여하는 방법은 무엇입니까? (0) | 2020.10.15 |
SMTP 서버에 보안 연결이 필요하거나 클라이언트가 인증되지 않았습니다. (0) | 2020.10.15 |
파이썬으로 URL을 요청하고 리디렉션을 따르지 않는 쉬운 방법이 있습니까? (0) | 2020.10.15 |