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

Laravel中如何在AssignedUnitController创建assigned_units表记录时同步更新users表的renting字段

Solution: Update Users Table While Creating Assigned Units in Laravel

Got it, let's fix this up so you can create an assigned_units record and update the corresponding user's renting field at the same time—with data consistency guaranteed. Here's how to adjust your controller logic:

Core Approach

We'll wrap both database operations in a Laravel database transaction to make sure either both actions succeed, or neither does (no partial updates!). Then we'll use the tenant_id from your request to target the right user and update their renting status with the value from your form.

Modified store Method Code

First, add the transaction facade import if you don't have it already, then update the method:

use Illuminate\Support\Facades\DB;

public function store(AssignUnitRequest $request) {
    if ($request->isMethod('POST')) {
        // Get validated data first (your AssignUnitRequest handles the rules)
        $validated = $request->validated();
        
        // Format the start date correctly
        $validated['start_date'] = Carbon::createFromFormat('d/m/Y', $validated['start_date']);

        try {
            // Wrap both actions in a transaction to ensure atomicity
            DB::transaction(function () use ($validated, $request) {
                // Create the new assigned unit record
                AssignedUnit::create($validated);

                // Find the target user and update their renting status
                $tenant = User::findOrFail($validated['tenant_id']);
                $tenant->update([
                    'renting' => $request->get('renting')
                ]);
            });

            // Success case: flash message and redirect
            Session::flash('success', 'Unit successfully assigned, tenant status updated!');
            return redirect()->route('admin.tenants.index');
        } catch (\Exception $e) {
            // Failure case: flash error and go back to form
            Session::flash('error_message', 'Assignment failed: ' . $e->getMessage());
            return back();
        }
    }
}

Key Details to Note

  • Transaction Safety: If creating the assigned_units record succeeds but updating the user fails (or vice versa), the transaction rolls back all changes—no messy inconsistent data left behind.
  • User Validation: findOrFail() ensures we only update an existing user. If the tenant_id is invalid, it throws an exception that triggers the rollback.
  • Cleaner Data Handling: We removed redundant $data assignments since $request->validated() already includes all fields your form submits (assuming your AssignUnitRequest is set up to accept tenant_id, prop_id, etc.).
  • Form Parameter: We directly use $request->get('renting') since you confirmed this value is passed from your form, which matches your users table's enum('renting', [0,1]) schema perfectly.

Quick Cleanup Tip

You can also simplify your original create method a tiny bit by using $data['renting'] = $request->old('renting', 1); instead of hardcoding 1—this retains the user's selected value if the form ever needs to reload due to errors.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.29 21:59:06