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

Laravel 5跨表取值写入新表报错:Undefined variable: id

问题排查与修复方案

首先,咱们来拆解这个Undefined variable: id错误的核心原因——你在jobcontroller@interested方法里直接用了$id变量,但这个变量根本没被定义;而且还有个逻辑漏洞:你用同一个$id去查找职位和用户信息,这显然不对,职位ID和用户ID是完全独立的两个值呀!

下面是一步步的修复步骤:

1. 给表单添加职位ID的隐藏字段

你的表单现在没有传递职位ID,控制器根本不知道用户感兴趣的是哪个职位。在Blade表单里加个隐藏字段,把当前职位的id传进去:

<form action="/submitresume" method="post">
    {{ csrf_field() }}
    <!-- 新增隐藏字段传递职位ID -->
    <input type="hidden" name="job_id" value="{{ $item->id }}">
    <div class="col-md-8 col-md-offset-2">
        <h2 class="display-2">{{$item->jobposition}}</h2>
        <p class="lead">{{$item->schoolname}}</p>
        <p class="text-info"> {{$item->jobdesc}} </p>
        <p class="text-info"> Salary: {{$item->prevemp}} </p>
        <p class="text-info"> Contact Information: {{$item->contact}} </p>
        <p class="lead">
            <button type="submit" class="btn btn-primary">Interested</button>
        </p>
    </div>
</form>

2. 修复Controller里的逻辑错误

接下来修正interested方法里的问题,重点是获取正确的职位ID和用户信息,同时遵循Laravel的开发规范:

use Illuminate\Http\Request;
use App\Job; // 确保引入正确的模型类
use App\UserProfile;
use App\Query;

public function interested(Request $request) {
    // 1. 验证提交的职位ID是否有效
    $request->validate([
        'job_id' => 'required|exists:jobs,id'
    ]);

    // 2. 检查用户是否登录,未登录则跳转至登录页
    if (!auth()->check()) {
        return redirect()->route('login')->with('error', '请先登录再提交申请');
    }
    $currentUser = auth()->user();

    // 3. 获取当前用户的个人信息(根据你的表结构调整关联字段,这里假设user_profiles表用user_id关联用户表)
    $userinfo = UserProfile::where('user_id', $currentUser->id)->first();
    // 如果user_profiles的主键是user_id,也可以用UserProfile::find($currentUser->id)

    // 4. 获取对应的职位信息
    $job = Job::find($request->job_id);

    // 5. 将数据存入querys表
    $query = new Query;
    $query->jobid = $job->id;
    $query->name = $userinfo->name;
    $query->age = $userinfo->age;
    $query->sex = $userinfo->sex;
    $query->degree = $userinfo->degree;
    $query->contactmail = $userinfo->contactmail;
    $query->bio = $userinfo->bio;
    $query->save();

    // 6. 提交成功后跳转回原页面并提示
    return redirect()->back()->with('success', '已成功提交职位申请!');
}

3. 额外的规范提示

  • 模型命名规范:Laravel的Eloquent模型类名应该用大驼峰(比如Job而非job,UserProfile而非userprofile),对应的数据表是小写复数形式,这样Eloquent能自动关联数据表,避免后续不必要的麻烦。
  • 路由优化:建议给路由起个名字,比如Route::post('/submitresume', 'JobController@interested')->name('job.interested');,之后表单里可以用action="{{ route('job.interested') }}",更灵活也更易维护。
  • 异常处理:如果用户没有完善个人信息(比如userinfo为null),可以加个判断提示用户先完善资料,避免报错。

这样修改后,点击Interested按钮应该就能正常把数据存入querys表啦!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 09:32:56