控制器沒有來自中間件的更改請求 (Controller doesnt have the alter request from the middleware)


問題描述

控制器沒有來自中間件的更改請求 (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 DanielDev DanielRwd)

參考文件

  1. Controller doesnt have the alter request from the middleware (CC BY‑SA 2.5/3.0/4.0)

#laravel-middleware #Laravel #PHP






相關問題

使用中間件進行表操作 laravel 5.1 (Using middleware for table manipulation laravel 5.1)

Laravel 中間件“僅”為每條路線觸發 (Laravel middlware 'only' fires for every route)

在 laravel 5.1 中檢查管理員角色 (Checking admin roles in laravel 5.1)

在laravel 5中使用中間件重定向循環 (redirect loop with middleware in laravel 5)

Laravel - 中間件後清空 $request (Laravel - Empty $request after middleware)

$request->user()->role 錯誤 - 試圖獲取非對象的屬性 ($request->user()->role errror - trying to get property of non-object)

檢測到 Laravel 中間件但未執行 (Laravel middleware detected but not executed)

將 Auth 中間件應用於所有 Laravel 路由 (Apply Auth Middleware to All Laravel Routes)

路由組內的功能 [laravel-passport] (Function inside route group [laravel-passport])

當我嘗試訪問主頁時,Laravel 不會重定向到登錄頁面 (Laravel does not redirect to login page when I try to access to home page)

控制器沒有來自中間件的更改請求 (Controller doesnt have the alter request from the middleware)

訂閱者中間件路由允許公眾查看所有受限頁面 (Subscriber middleware route allowing public to view all restricted pages)







留言討論