如何将变量从中间件传递到控制器或执行此类中间件的路由?我看到了一些帖子,内容是在请求中添加它,如下所示:
$request->attributes->add(['key' => $value);
还有人建议使用flash:
Session::flash('key', $value);
但我不确定这是否是最佳实践,或者是否有更好的方法来做到这一点?以下是我的中间件和路径:
namespace App\Http\Middleware;
use Closure;
class TwilioWorkspaceCapability
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $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?...
]);
}]);
仅供参考,我之所以决定使用中间件,是因为我计划在令牌的生命周期中缓存令牌,否则这将是一个可怕的实现,因为我会在每次请求时请求一个新令牌.