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

15

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

$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?...
    ]);
}]);

我使用中间件的原因是计划在Token生命周期内缓存它,否则这将是一种可怕的实现方式,因为我需要在每个请求中请求一个新的Token。

2个回答

9

像这样传递键值对

$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');

6
对于 Laravel 5,以下是如何在请求中添加参数的方法:$request->attributes->add(['myAttribute' => 'myValue']); - Ben Dubuisson

2
我会利用Laravel的IOC容器来完成这个任务。
在你的AppServiceProvider的register方法中。
$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(),
    ]);
}]);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接