Laravel房屋租赁系统报错:Attempt to assign property 'Tenant_id' on null
问题分析与解决方案
你遇到的Attempt to assign property 'Tenant_id' on null错误,核心原因是代码中$house变量为null——你没有正确获取到需要租赁的房屋模型实例,同时整个业务逻辑存在多处偏差,以下是针对性修正:
1. 修正路由配置
当前路由传递的是user参数,但我们需要操作的是房屋资源,修改路由如下:
Route::group(['prefix'=>'client', 'middleware'=>['isClient','auth','PreventBackHistory']], function(){ // 保留原有其他路由... // 修改rent路由,接收house参数并设置更清晰的路由名称 Route::post('house/{house}/rent',[HouseController::class,'rent'])->name('house.rent'); });
2. 修正HouseController的rent方法
原方法完全错误地从请求中获取Tenant_id,正确做法是利用Laravel路由模型绑定直接获取房屋实例:
public function rent(Request $request, House $house) { // 检查房屋是否已被租赁,避免重复操作 if (!is_null($house->Tenant_id)) { return redirect()->back()->with('error', '该房屋已被租赁'); } // 为当前房屋设置租户ID为登录用户ID $house->Tenant_id = Auth::user()->id; $house->save(); return redirect()->back()->with('success', '房屋租赁申请提交成功'); }
3. 修正视图代码
原视图循环用户的逻辑完全不符合业务需求,应该遍历房屋列表,为每个可租赁的房屋显示Rent按钮:
{{-- 假设你已将$houses变量传递到视图 --}} @foreach ($houses as $house) @if (is_null($house->Tenant_id)) <form method="post" action="{{ route('house.rent', $house) }}"> @csrf <button class="button" type="submit">Rent</button> </form> @else <span class="text-muted">已被租赁</span> @endif @endforeach
- 移除了无意义的用户循环,改为遍历房屋资源
- 通过路由传递房屋实例,生成正确的提交URL
- 添加了房屋租赁状态判断,避免重复操作
内容的提问来源于stack exchange,提问作者sofija21
相关产品推荐
相关产品推荐

