Laravel 5 - 从控制器级别的所有请求对象中删除参数

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

Laravel 5 - Remove Parameter From All Request Objects at Controller Level

laravellaravel-5laravel-5.2

提问by Lloyd Banks

I have URLs that look like:

我的网址如下:

http://example.com/api/user?id=45&name=mike&api_token=2348283
http://example.com/api/project?id=5&description=first&api_token=2348283
etc...

In my controllers, I have functions that look like:

在我的控制器中,我有如下功能:

public function user_get_endpoint(Request $request){

    $request = $request->toArray();
    return UserModel::where($request)->get()->toArray();

}

The above will currently break since the $requestobject contains a property called api_tokenwhich does not exist in the usertable. I am using the api_tokenin a middleware to check for authentication.

由于该$request对象包含一个api_tokenuser表中不存在的被调用的属性,因此上述内容目前将中断。我api_token在中间件中使用 来检查身份验证。

I can manually unset the api_tokenproperty in each of my API functions by using unset($request['api_token'], but I'd like to avoid that if possible.

我可以使用 手动取消api_token每个 API 函数中的属性设置unset($request['api_token'],但如果可能,我想避免这种情况。

Is there anyway to do this application wide or at a class or controller level?

无论如何要在整个应用程序范围内或在类或控制器级别执行此应用程序吗?

回答by Shams Reza

Laravel provides add and remove functions to add and remove new properties to the request object respectively.

Laravel 提供了 add 和 remove 函数来分别向请求对象添加和删除新属性。

 $request->request->add(['api_token' => 'api_token']); // to add new property to $request
    $request->request->remove('api_token'); // to remove property from $request

回答by bishop

Perhaps you want global middleware?

也许您想要全局中间件

First arrange for the middleware to run on all routes:

首先安排中间件在所有路由上运行:

// routes.php
$app->middleware([
    App\Http\Middleware\Apitoken::class
]);

Then define what the middleware should do:

然后定义中间件应该做什么:

// src/App/Http/Middleware/Apitoken.php
<?php
namespace App\Http\Middleware;

use Closure;

class Apitoken
{
    public function handle($request, Closure $next)
    {
        unset($request['api_token']);

        return $next($request);
    }
}

回答by justnajm

Method 1

方法一

$request->except(['key1','key2',....])

provides an easy way to skip unwanted keys, similarly

类似地,提供了一种跳过不需要的键的简单方法

Method 2

方法二

$request->only(['key3','key4',....])

provides an easy way to skip all others unwanted keys, I find both reasonably good for almost all scenarios

提供了一种跳过所有其他不需要的键的简单方法,我发现它们几乎适用于所有场景

回答by fico7489

A solution that works for all HTTP Methods (not only for GET and HEAD) :

适用于所有 HTTP 方法的解决方案(不仅适用于 GET 和 HEAD):

$except = ['api_token'];
$request = request();
$cleanup = $request->except($except);
$request->query = new \Symfony\Component\HttpFoundation\ParameterBag($cleanup);

回答by Amit Gupta

Ideally, you should send your api_tokenin request headers instead of Uri params.

理想情况下,您应该发送api_token请求标头而不是 Uri 参数。

If you are using Laravel's auth:apiMiddleware for authentication then you can send api_tokenin headers as:

如果您使用 Laravel 的auth:api中间件进行身份验证,那么您可以将api_token标头发送为:

$response = $client->request('GET', '/api/user', [
    'headers' => [
        'Accept' => 'application/json',
        'Authorization' => 'Bearer '.$accessToken,
    ],
]);

Then api_token will never come in your Uri params.

那么 api_token 永远不会出现在你的 Uri 参数中。

回答by Rwd

As @JanWillem said in the comments you can use except()which will remove the params you pass to it:

正如@JanWillem 在评论中所说,您可以使用except()它将删除您传递给它的参数:

public function user_get_endpoint(Request $request){

    return UserModel::where($request->except('api_token'))->get();
}

https://laravel.com/docs/5.2/requests#retrieving-inputand then scroll down to Retrieving A Portion Of The Input Data

https://laravel.com/docs/5.2/requests#retrieving-input然后向下滚动到Retrieving A Portion Of The Input Data

Furthermore, you don't have to use toArray()with the response as Laravel will automatically do this for you.

此外,您不必使用toArray()响应,因为 Laravel 会自动为您执行此操作。

Hope this helps!

希望这可以帮助!