[英]Can we use same route for authenticated and non-authenticated users in laravel with same controller and same view?
// route which should be used by authenticated and unauthenticated user
Route::get('user/send-parcel', 'User\SenderController@sendParcerl');
我試圖在 web 中添加這個路由(在這個 auth 中間件之外)。 它工作正常,但在我的控制器中,如果用戶未登錄,我必須添加用戶 ID,如果用戶未登錄,則user_id
字段應包含NULL
的值。
$user = Auth::user();
$parcel->user_id = isset($user) ? $user->id : NULL;
主要問題是,如果我將路由放在 Auth 中間件之外,它將無法在我的控制器中獲得 Auth。 因此該代碼適用於未經身份驗證的用戶,但對於經過身份驗證的用戶,它還將NULL
放入user_id
字段
簡單的回答是,可以。
如何工作,如果您查看此頁面: https : //laravel.com/docs/5.8/authentication#authentication-quickstart
您將看到一節,說明如何檢查用戶是否登錄。
確定當前用戶是否已通過身份驗證
要確定用戶是否已經登錄到您的應用程序,可以在Auth外觀上使用check方法,如果該用戶通過了身份驗證,則該方法將返回true:
use Illuminate\Support\Facades\Auth;
if (Auth::check()) {
// The user is logged in...
}
因此,在您的控制器中,添加Auth外觀后,您可以執行以下操作:
if (Auth::check()) {
// do something with an authenticated user
} else {
// do something with a non-authenticated user
}
// shared code between all kind of users
如Laravel文檔中所述,大多數時候建議使用中間件並將其重定向到其他控制器。
是的你可以。 在您的控制器中,您必須使用自己的中間件添加構造。
public function __construct()
{
$this->middleware(function ($request, $next) {
$this->user = $request->user('api');
return $next($request);
});
}
這里最重要的部分是
$request->user('api');
如果您的路由是公開的(沒有任何中間件進行限制),它將使用所有可公開訪問的信息,因此不會有會話、令牌等。 $request->user(); 的正常使用; 不會工作。
幸運的是$request->user()可以接受一個參數
/**
* Get the user making the request.
*
* @param string|null $guard
* @return mixed
*/
public function user($guard = null)
{
return call_user_func($this->getUserResolver(), $guard);
}
因此,如果您執行$request->user('api') ,它將使用 api 保護檢索用戶,因為這些信息可以在 'api' 保護中訪問。
現在在您的代碼中,您可以檢查 $this->user 是否為 null(null 它將不是登錄用戶,對象它將是登錄用戶)。
資料來源:答案 #1,第 3 點這里https://www.py4u.net/discuss/32099
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.