問題描述
控制器沒有來自中間件的更改請求 (Controller doesnt have the alter request from the middleware)
我有一個自定義中間件可以編輯這樣的請求:
public function handle($request, Closure $next)
{
$profileLocal = ProfileLocal::where(
'id', JWTHelper::tokenExtractProfileLocalID($request‑>token)
)‑>with('status')‑>first();
if (empty($profileLocal) || $profileLocal‑>status‑>email_verified == 0 || $profileLocal‑>status‑>blocked == 1) {
return $this‑>respondError('You dont have access to this store', 336);
}
$request‑>profileLocal = $profileLocal;
return $next($request);
}
但是,當我嘗試訪問 $request‑>profileLocal
在我的控制器中:
public function deviceSet(DeviceRequest $request)
{
dd($request‑>profileLocal);
}
如果我嘗試 dd(request()‑>profileLocal)
它工作正常,即使在我的 DeviceRequest 中我也會返回 null?有誰知道我在這裡可能做錯了什麼?我注意到如果我在控制器中使用 request()‑>profileLocal
它會按預期工作
參考解法
方法 1:
I was told that if I use:
$request‑>attributes‑>add(['profileLocal' => $profileLocal]);
In my middleware and then access it using:
$request‑>attributes‑>get('profileLocal')
It works, I dont know if this is the correct way though.
方法 2:
If you want to add add a value to the request and be able to access it as a property you can add it to the underlying request
property:
$request‑>request‑>add([
'profileLocal' => $profileLocal
]);
// or $request‑>request‑>add(compact('profileLocal'))
Then you'll be able to access the value in your controller with:
$request‑>profileLocal
This value will also be included when you call methods like all()
or input()
.
(by Dev Daniel、Dev Daniel、Rwd)