Laravel中如何在AssignedUnitController创建assigned_units表记录时同步更新users表的renting字段
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_unitsrecord 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 thetenant_idis invalid, it throws an exception that triggers the rollback. - Cleaner Data Handling: We removed redundant
$dataassignments since$request->validated()already includes all fields your form submits (assuming yourAssignUnitRequestis set up to accepttenant_id,prop_id, etc.). - Form Parameter: We directly use
$request->get('renting')since you confirmed this value is passed from your form, which matches youruserstable'senum('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

