Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

noblemfd's avatar

How to delete record based on condition

In my Laravel-5.8, I have these three (3) models:

class Parameter extends Model
{    
    protected $table = 'parameters';
    protected $primaryKey = 'id';
    protected $fillable = [
                  'max_score',
                  'min_score',
                  'identity_id',
              ];

    public function identity()
    {
        return $this->belongsTo('App\Models\Identity','identity_id');
    }
}


class Identity extends Model
{
    protected $table = 'identity';

    protected $fillable = [
              'id',
              'name',
          ];

    public function goals()
    {
       return $this->hasMany('App\Models\Goal');
    }  

    public function parameter()
    {
       return $this->hasOne(Parameter::class, 'identity_id');
    }    
}


class Goal extends Model
{
    protected $table = 'goals';

    protected $fillable = [
                  'id',
                  'identity_id',
                  'title',
              ]; 

    public function identity()
    {
        return $this->belongsTo('App\Models\Identity','identity_id');
    }        
}

From the model, Identity has a foreign key (identity_id) in Parameter, also Identity has foreign key (identity_id) in Goal.

I have this controller in Identity:

public function destroy($id)
{
    try 
    {          
        $identity = Identity::findOrFail($id);
        $identity->delete();
        Session::flash('success', 'Record deleted successfully.');
        return redirect()->back();
    } 
    catch (Exception $exception) {
            Session::flash('error', 'Record delete failed!.');
            return redirect()->back();
    }       
}   

I want the user to delete Identity Record based on these conditions:

  1. As the user tries to delete Identity, the application should check Parameter table and also delete the record where identity_id foreign key exist.

  2. Secondly, if record with identity_id exists in Goal table, the application should prevent the delete.

How do I adjust

public function destroy($id) 

to achieve these?

Thanks

0 likes
1 reply
chaudigv's avatar
chaudigv
Best Answer
Level 16

Give this a shot

$identity = Identity::findOrFail($id);

// if record with identity_id exists in Goal table, the application should prevent the delete.
if($identity->goals->count() == 0) {
    // also delete the record where identity_id foreign key exist
    $identity->parameter()->delete(); 
    $identity->delete();
    Session::flash('success', 'Record deleted successfully.');
} else {
    Session::flash('error', 'Goals exists.');
}

Please or to participate in this conversation.