You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Laravel中登录或注册跳转后如何保留表单已填写的字段内容

Laravel 实现登录后返回表单并保留填写内容操作步骤

步骤1:配置路由和中间件顺序

首先在routes/web.php中配置卡片相关路由,注意提交路由需要先经过数据暂存中间件,再经过身份校验中间件:

// 卡片表单展示路由(无需登录即可访问)
Route::get('/card/create', [\App\Http\Controllers\CardController::class, 'create'])->name('card.create');
// 卡片提交路由(先暂存表单数据,再校验登录状态)
Route::post('/card/store', [\App\Http\Controllers\CardController::class, 'store'])
    ->name('card.store')
    ->middleware('save.form.data', 'auth');

步骤2:创建表单数据暂存中间件

运行命令生成自定义中间件:

php artisan make:middleware SaveFormDataForUnauthenticated

打开生成的app/Http/Middleware/SaveFormDataForUnauthenticated.php,替换为以下代码:

<?php
namespace App\Http\Middleware;

use Closure;
use Illuminate\Support\Facades\Auth;

class SaveFormDataForUnauthenticated
{
    public function handle($request, Closure $next)
    {
        if (!Auth::check()) {
            // 提取表单页路径作为session存储键
            $previousPath = ltrim(parse_url(url()->previous(), PHP_URL_PATH), '/');
            // 暂存用户提交的所有表单数据
            session()->put('form_data.'.$previousPath, $request->all());
            // 手动指定登录后跳转地址为表单页,避免跳转POST路由报错
            session()->put('url.intended', url()->previous());
        }
        return $next($request);
    }
}

打开app/Http/Kernel.php,在$routeMiddleware数组中注册中间件:

protected $routeMiddleware = [
    // 原有其他中间件保留
    'save.form.data' => \App\Http\Middleware\SaveFormDataForUnauthenticated::class,
];

步骤3:确认登录注册跳转逻辑

Laravel自带的Breeze/UI/Jetstream认证脚手架默认已经使用redirect()->intended()逻辑,会优先跳转到我们之前存储的表单页地址。如果是自定义的登录/注册逻辑,只需要在用户认证成功后返回以下内容即可:

// 第二个参数为默认跳转地址, intended 方法优先读取session中存储的目标地址
return redirect()->intended(route('card.create'));

步骤4:表单数据回填

打开CardController的create方法,读取暂存的表单数据传给视图:

public function create()
{
    // 读取当前页面对应的暂存表单数据,不存在则返回空数组
    $formData = session()->get('form_data.'.request()->path(), []);
    // 读取后删除session数据,避免下次打开表单重复回填旧内容
    session()->forget('form_data.'.request()->path());
    
    return view('card.create', compact('formData'));
}

在Blade表单模板中给所有输入框加上回填逻辑即可:

{{-- 不要忘记csrf令牌 --}}
@csrf
<input type="text" name="title" value="{{ old('title', $formData['title'] ?? '') }}">
<textarea name="desc">{{ old('desc', $formData['desc'] ?? '') }}</textarea>
{{-- 其他字段按同样格式配置即可 --}}

内容的提问来源于stack exchange,提问作者Cesar Osuna

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.03 05:27:02