Laravel 5 / Lumen Request Header?

别等时光非礼了梦想. 提交于 2019-12-03 09:52:12

Try to change the Illuminate\Http\Request to Request.

- use Illuminate\Http\Request;
+ use Request;

You misunderstand the Laravel request object on two levels.

First, the error you are getting is because you were referencing the object instead of the Facade. Facades have a way of forwarding static method calls to non-static methods.

Second, you are sending the value as a header but are trying to access the request parameters. This will never give you what you want.

Here is a simple way to see an example of what you want by creating a test route like so:

Route::match(['get','post'], '/test', function (Illuminate\Http\Request $request) {
    dd($request->headers->all());
});

Post to this route and you will see your headers, one of which will be pubapi. Pay attention that the route method definition matches how you are submitting the request (ie GET or POST).

Let's apply this to the controller, ArticleController:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class ArticleController extends Controller
{
    public function index(Request $request)
    {
        $pubapi = $request->header('pubapi'); // string
        $headers = $request->headers->all(); // array
        /*
          $pubapi === $headers['pubapi']
        */
    }
}

Using

echo app('request')->header('pubapi');

Instead of

echo Request::header('pubapi');

Seemed to work perfect. Could someone provide additional explanation to why this worked and my original method didn't?

Shahrukh Anwar

Actually you are calling it statically, that's why it is not getting appropriate Request class and throwing error, can do as follows

use Illuminate\Http\Request;

//inside your controller
class YourClass extends Controller{
   public function yourFunction(Request $request){
        //for getting all the request
        dd($request->all());

        //for getting header content
        dd($request->header('pubapi'));
   }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!