2016-12-07 88 views
0

我已經爲API創建了我自己的中間件。以下是我爲獲得基於該請求有效的用戶信息碼PARAMS access_token如何從中間件獲取變量?

namespace App\Http\Middleware; 

use Closure; 
use App\Exceptions\GeneralException; 
use App\Models\Access\User\User; 

class authNS 
{ 
    /** 
    * Handle an incoming request. 
    * 
    * @param \Illuminate\Http\Request $request 
    * @param \Closure $next 
    * @return mixed 
    */ 
    public function handle($request, Closure $next) 
    { 
     try { 

      $user = User::where("access_token",$request->header('access-token'))->with('details')->first(); 

     } catch (Exception $e) { 

      return response()->json(['error'=>'Something is wrong']); 

     } 

     return $next($request); 

    } 
} 

但如何將我的Controller內訪問此$user變量?

回答

1

您可以使用onceUsingId()將用戶登錄到單個請求的應用程序中。沒有會議或cookies將被利用,這意味着建立一個無狀態的API時,這種方法可能會有所幫助:

因此,在您middleware你可以使用它作爲:

$user = User::where("access_token",$request->header('access-token'))->first(); 

if($user) { 
    auth()->onceUsingId($user->id); 
} 

然後在你的控制器,你可以使用它爲:

auth()->user() 

Docs

+0

太謝謝你了。它工作完美 – devmyb

+0

@iCode,我需要你的幫助。看看這裏:http://stackoverflow.com/questions/41030097/how-to-add-some-textfield-in-form-register-laravel-generator-infyom –