laraveleloquent

Laravel forbid updating row if its referenced in another table


say Table A and Table B (table B has a foreign key a_id) I want to be able to update a row in A as long as it's not ref in B I already did it but I'm looking for a better approach.

My approach

$referencesInB = TableB::where('a_id', $id)->exists();
if ($referencesInB) {
    return response()->json(['error' => 'Cannot update'], 403);
}
$rowA->update($request->all());

Solution

  • $referencesInB = TableB::where('a_id', $id)->exists();
    

    You can avoid the extra query check above(saving us a few milliseconds or more) by eager loading the relation and checking if the relation actually loaded. So, it all happens with 1 query instead of 2 eliminating the N + 1 query issue docs.

    <?php
    
    $rowA = TableA::with('table_b')->find($id);
    
    if ($rowA->relationLoaded('table_b')) {
      return response()->json(['error' => 'Cannot update'], 403);
    }
    
    $rowA->update($request->all());