skip to Main Content

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());

2

Answers


  1. You can do it upstream where you first get $rowA

    $rowA = TableA::whereDoesntHave('B')->findOrFail($id);
    
    //or
    
    $rowA = AClass::whereDoesntHave('B')->find($id);
    if (!$rowA) {
        return response()->json(['error' => 'Cannot update'], 403);
    }
    

    'B' is the name of the relation difined in TableA model class

    Login or Signup to reply.
  2. $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());
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search