简体   繁体   English

Laravel 5.4 Dingo路线绑定

[英]Laravel 5.4 Dingo Route Binding

I'm attempting to bind a function to the routing so it takes effect globally. 我试图将功能绑定到路由,以使其在全局范围内生效。 Basically I'm using Hashids to obfuscate the IDs, and want to be able to decode the ID on the route level so I don't need to do it everywhere the ID is uses in different controllers. 基本上,我使用Hashids对ID进行模糊处理,并希望能够在路由级别上对ID进行解码,因此我无需在ID用于不同控制器中的任何地方都需要这样做。

I've attempted to do the following at the top of the api routes file: 我试图在api路由文件的顶部执行以下操作:

api.php api.php

<?php

    use Dingo\Api\Routing\Router;
    use Hashids\Hashids;

    Route::bind('id', function ($id) {
        return Hasher::decode($id);
    });

    /** @var Router $api */
    $api = app(Router::class);

But it doesn't seem to have any effect. 但这似乎没有任何作用。

I have a couple of routes that use the ID I want to decode at the bottom of the routes file: 在路由文件底部,我有几条使用我要解码的ID的路由:

$api->get('leads/{id}', 'App\\Api\\V1\\Controllers\\LeadController@show');
$api->put('leads/update/{id}', 'App\\Api\\V1\\Controllers\\LeadController@update');

Really at a loss as to how to get this to work, I've tried using $api->bind and others but they all call undefined functions. 关于如何使它工作真的很茫然,我尝试使用$ api-> bind和其他方法,但是它们都调用了未定义的函数。

Sure this is an easy thing, but I'm just starting out with Laravel so this is a bit beyond me at this point. 当然这是一件容易的事,但是我只是从Laravel开始,所以这一点超出了我的理解。

Many thanks! 非常感谢!


Based on the hint that Serge gave me, I've attempted to move this functionality into Middleware, but still due to a full lack of understanding, this isn't working. 基于Serge给我的提示,我尝试将此功能移入中间件,但由于仍然缺乏理解,因此无法正常工作。

I have the following middleware: 我有以下中间件:

<?php

namespace App\Http\Middleware;

use Closure;
use Junity\Hashids\Facades\Hashids;

class DecodeHashids
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {

        if($request->has('id'))
            $request->id = Hasher::decode($request->id);

        return $next($request);
    }
}

I've added it to Kernal.php: 我已将其添加到Kernal.php:

protected $middlewareGroups = [
        'web' => [
            \App\Http\Middleware\EncryptCookies::class,
            \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
            \Illuminate\Session\Middleware\StartSession::class,
            \Illuminate\View\Middleware\ShareErrorsFromSession::class,
            \App\Http\Middleware\VerifyCsrfToken::class,
            \Illuminate\Routing\Middleware\SubstituteBindings::class,
        ],

        'api' => [
            'throttle:60,1',
            'bindings',
            'decode',
        ],
    ];

    /**
     * The application's route middleware.
     *
     * These middleware may be assigned to groups or used individually.
     *
     * @var array
     */
    protected $routeMiddleware = [
        'auth' => \Illuminate\Auth\Middleware\Authenticate::class,
        'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
        'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
        'can' => \Illuminate\Auth\Middleware\Authorize::class,
        'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
        'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,

        'jwt.auth' => GetUserFromToken::class,
        'jwt.refresh' => RefreshToken::class,

        'decode' => \App\Http\Middleware\DecodeHashids::class,
    ];
}

and added it in the api routes file as so: 并将其添加到api路由文件中,如下所示:

$api->group(['middleware' => 'jwt.auth'], function(Router $api) {
        $api->get('protected', function() {
            return response()->json([
                'message' => 'Access to protected resources granted! You are seeing this text as you provided the token correctly.'
            ]);
        });

        $api->get('refresh', [
            'middleware' => 'jwt.refresh',
            function() {
                return response()->json([
                    'message' => 'By accessing this endpoint, you can refresh your access token at each request. Check out this response headers!'
                ]);
            }
        ]);

        $api->group(['middleware' => 'decode'], function(Router $api) {
            $api->get('leads/{id}', 'App\\Api\\V1\\Controllers\\LeadController@show');
        });

I get no errors, but the ID is not decoded when it passes through to the controller. 我没有收到任何错误,但是当ID传递给控制器​​时,它没有被解码。

Thanks to the help from Serge, I managed to complete the Middleware. 多亏了Serge的帮助,我才得以完成中间件。

Middleware as below, it updates the Route ID Parameter with the decoded value, and this Middleware is added to the Kernal. 如下所示的中间件,它使用解码后的值更新Route ID参数 ,并将此中间件添加到内核中。

<?php

namespace App\Http\Middleware;

use Closure;
use Hashids;

class DecodeHashids
{
    public function handle($request, Closure $next)
    {

        if($request->route()->parameters('id'))
            $request->route()->setParameter('id', Hashids::decode($request->id));

        return $next($request);
    }
}

Then in the API route file, I added a new group that uses the 'decode' Middleware: 然后在API路由文件中,添加了一个使用“解码”中间件的新组:

$api->group(['middleware' => 'decode'], function(Router $api) {
    $api->get('leads/{id}', 'App\\Api\\V1\\Controllers\\LeadController@show');
});

Can then of course add as many routes to this group where parameters need decoded. 然后当然可以向需要解码参数的组添加尽可能多的路由。

Thanks Serge and the Laravel community for the help and responses on here and other sites. 感谢Serge和Laravel社区在此以及其他站点上提供的帮助和回复。 Hopefully this will help others. 希望这会帮助其他人。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM