Laravel -将变量从中间件传递到控制器/路由



如何将变量从中间件传递到执行此类中间件的控制器或路由?我看到一些帖子关于将其附加到请求中,像这样:

$request->attributes->add(['key' => $value);

也有人建议使用flash:

Session::flash('key', $value);

但我不确定这是否是最佳实践,或者是否有更好的方法来做到这一点?这是我的中间件和路由:

namespace AppHttpMiddleware;
use Closure;
class TwilioWorkspaceCapability
{
    /**
     * Handle an incoming request.
     *
     * @param  IlluminateHttpRequest $request
     * @param  Closure $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $workspaceCapability = new Services_Twilio_TaskRouter_Workspace_Capability("xxxxx", "xxxx", "xxxx");
        $workspaceCapability->allowFetchSubresources();
        $workspaceCapability->allowDeleteSubresources();
        $workspaceCapability->allowUpdatesSubresources();
        $token = $workspaceCapability->generateToken();
        //how do I pass variable $token back to the route that called this middleware
        return $next($request);
    }
}
Route::get('/manage', ['middleware' => 'twilio.workspace.capability', function (Request $request) {
    return view('demo.manage', [
        'manage_link_class' => 'active',
        'twilio_workspace_capability' => //how do I get the token here?...
    ]);
}]);

仅供参考,我决定使用中间件的原因是因为我计划在其生命周期内缓存令牌,否则这将是一个可怕的实现,因为我将在每个请求上请求一个新的令牌。

像这样传递键值对

$route = route('routename',['id' => 1]);

或你的行动

$url = action('UserController@profile', ['id' => 1]);

可以使用with

将数据传递给视图
 return view('demo.manage', [
    'manage_link_class' => 'active',
    'twilio_workspace_capability' => //how do I get the token here?...
]) -> with('token',$token);
中间件中的

 public function handle($request, Closure $next)
 {
    $workspaceCapability = new .....
    ...
    $request -> attributes('token' => $token);
    return $next($request);
 }

在你的控制器

 return Request::get('token');

我会利用laravel的IOC容器。

在你的AppServiceProvider的注册方法

$this->app->singleton(TwilioWorkspaceCapability::class, function() { return new TwilioWorkspaceCapability; });

这意味着无论你在你的应用程序中DI(依赖注入)这个类,都会被注入相同的实例。

在TwilioWorkspaceCapability类中:

class TwilioWorkspaceCapability {
    /**
     * The twillio token
     * @var string
     */
    protected $token;

    /**
     * Get the current twilio token
     * @return string
     */
    public function getToken() {
        return $this->token;
    }
    ... and finally, in your handle method, replace the $token = ... line with:
    $this->token = $workspaceCapability->generateToken();
}

然后,在你的路由中:

Route::get('/manage', ['middleware' => 'twilio.workspace.capability', function (Request $request, TwilioWorkspaceCapability $twilio) {
    return view('demo.manage', [
        'manage_link_class' => 'active',
        'token' => $twilio->getToken(),
    ]);
}]);

最新更新