Search code examples
laravel

Laravel Data Deletion


How can I prevent data deletion if the data of one data-table is used in another data-table as foreign key in Laravel? This is a controller from where I have to delete data.

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Theme;

class ThemeController extends Controller
{

    public function destroy($id)

        Theme::destroy($id);
        return redirect()->route('theme.index')->withFlashSuccess('Theme profile is deleted successfully.');
    }
}

How can I apply a condition to stop the deletion the data in this controller, if this controller data is used in another controller?


Solution

  • Copy and replace with your current function

      public function destroy($id)
    {
        $foreignKeyCheck = DB::table('general_agreement_theme ')
                ->where('theme_id' ,$id)->get();
    
        if($foreignKeyCheck->isEmpty())
        {
            Theme::destroy($id);
            return redirect()->route('theme.index')->withFlashSuccess('Theme profile is deleted successfully.');
        }else{
            return redirect()->route('theme.index')->withFlashSuccess('Theme profile is deleted successfully.');
        }
            
    }
    

    And don't forget to import

    use Illuminate\Support\Facades\DB;
    

    at the top of the controller.