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

Laravel Jetstream:无需修改Vendor文件修改控制器方法返回值

需求说明

需要为Laravel Jetstream的UserProfileController的show方法返回的视图数据添加'video' => $request->user()->video字段,但不能直接修改vendor/laravel/jetstream/src/Http/Controllers/Inertia/UserProfileController.php文件,避免框架更新时丢失修改。

原控制器方法代码:

public function show(Request $request)
{
    $this->validateTwoFactorAuthenticationState($request);

    return Jetstream::inertia()->render($request, 'Profile/Show', [
        'confirmsTwoFactorAuthentication' => Features::optionEnabled(Features::twoFactorAuthentication(), 'confirm'),
        'sessions' => $this->sessions($request)->all(),
    ]);
}

期望修改后的代码效果:

public function show(Request $request)
{
    $this->validateTwoFactorAuthenticationState($request);

    return Jetstream::inertia()->render($request, 'Profile/Show', [
        'confirmsTwoFactorAuthentication' => Features::optionEnabled(Features::twoFactorAuthentication(), 'confirm'),
        'sessions' => $this->sessions($request)->all(),
        'video' => $request->user()->video,
    ]);
}
解决方案:继承并重写控制器

通过继承Jetstream的原控制器,自定义控制器并覆盖show方法,再修改路由指向自定义控制器,即可实现需求且不修改vendor文件。

步骤1:创建自定义控制器

在app/Http/Controllers目录下创建UserProfileController.php,继承Jetstream的原控制器并覆盖show方法:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Laravel\Jetstream\Http\Controllers\Inertia\UserProfileController as JetstreamUserProfileController;
use Laravel\Jetstream\Jetstream;
use Laravel\Jetstream\Features;

class UserProfileController extends JetstreamUserProfileController
{
    public function show(Request $request)
    {
        $this->validateTwoFactorAuthenticationState($request);

        return Jetstream::inertia()->render($request, 'Profile/Show', [
            'confirmsTwoFactorAuthentication' => Features::optionEnabled(Features::twoFactorAuthentication(), 'confirm'),
            'sessions' => $this->sessions($request)->all(),
            'video' => $request->user()->video, // 新增需要的字段
        ]);
    }
}

步骤2:重写路由指向自定义控制器

打开routes/web.php文件,添加以下路由(确保放在Jetstream路由加载语句之后,比如require __DIR__.'/jetstream.php';之后),覆盖原Jetstream的个人资料路由:

use App\Http\Controllers\UserProfileController;

Route::get('/user/profile', [UserProfileController::class, 'show'])->name('profile.show');

这样,当访问个人资料页面时,会调用自定义控制器的show方法,返回包含video字段的视图数据,同时后续更新Jetstream时不会丢失修改。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 05:51:32