noblemfd
1 week ago
144
5
Laravel

How to prevent the delete of table row that has it's id in another table

Posted 1 week ago by noblemfd

I have these models:

class GoalType extends Model
{
    protected $table = 'goal_type';
    protected $primaryKey = 'id';
    protected $fillable = [
              'name',
          ];

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

class Goal extends Model
{
    protected $table = 'goals';
    protected $fillable = [
              'id',
              'goal_type_id',
              'goal_title',
       ];

    public function goaltype()
    {
        return $this->belongsTo('App\GoalType','goal_type_id');
    }
}

Controller: GoalType

public function destroy(Request $request, $id)
{
    DB::beginTransaction(); 
    try{
        $goaltype = GoalType::find($id);
        $goaltype->delete();
        Session::flash('success', Goal deleted successfully.');
        return redirect()->route('goal_types.index');
  }          
    catch (Exception $exception) 
    { 
        Log::error($exception); 
        DB::rollback();
        Session::flash('error', 'Action failed! Please try again');
        return redirect()->route('goal_types.index'); 
    }              
}

The model GoalType has it's foreign key in Goal. The code above for delete is working. But without using DB foreign key relationship, if id (goal_type_id) is being used in Goal, it should prevent delete and display a message.

How do I achieve this?

Please sign in or create an account to participate in this conversation.