一般會使用 URL::previous() 、 redirect()->intended()
或是靠 session 去處理,
這邊在提供另一個方法!
新增 auth.redirect:web
如果有需求,可以在 $middlewarePriority 調整執行順序!
route/webs.php
Route::group(['middleware' => 'auth.redirect:web', 'auth:web']
app/Http/Kernel.php
protected $routeMiddleware = [ 'auth.redirect' => \App\Http\Middleware\RedirectToAuthenticated::class, ....];
處理未登入狀態,進入auth頁面時
新增 app/Http/Middleware/RedirectToAuthenticated.php
<?php namespace App\Http\Middleware; use Closure; use Illuminate\Http\Request; use Illuminate\Support\Facades\Auth; class RedirectToAuthenticated { /** * Handle an incoming request. * * @param \Illuminate\Http\Request $request * @param \Closure $next * @param string|null ...$guards * @return mixed */ public function handle(Request $request, Closure $next, $auth) { $redirectTo = $_SERVER['REQUEST_URI']; if (!Auth::guard($auth)->check()) { return redirect(webPath(sprintf('login?redirect=%s', $redirectTo))); } return $next($request); } }
處理登入後的行為
app/Providers/FortifyServiceProvider.php 的 register() 設置
$this->app->instance(LoginResponse::class, new class implements LoginResponse { public function toResponse($request) { if ($request->get('redirect', null)) { return redirect(webPath($request->get('redirect'))); } return redirect()->route('web.home'); } });