Skip to content

From Small to BIGGER

Menu
  • Home
  • About Us
  • Portofolio
  • Contact
Menu

Laravel – Delete relation data and backup records to JSON

Posted on September 24, 2022September 24, 2022 by kura

Create class helper on folder App sample class

<?php

namespace App\Helpers;

use Carbon\Carbon;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;

class QueryBuilder {

    public static function deleteRelation($tableRelations, $params, $tableTarget)
    {
        DB::transaction(function () use ($tableRelations, $params, $tableTarget) {
            $path = 'records_deleted/' . date('Ymd') . '/';

            foreach ($tableRelations as $key => $tableRelation) {
                $rows = DB::table($tableRelation)->where($params['field'], $params['value']);

                $jsonRelation = Str::slug($tableRelation . ' ' . Carbon::now(), '_') . '.json';

                Storage::disk('local')->put($path . $jsonRelation, json_encode($rows->get()->toArray(), TRUE));

                $rows->delete();
            }

            $row = DB::table($tableTarget)->where('id', $params['value']);

            $jsonTarget = Str::slug($tableTarget . ' ' . Carbon::now(), '_') . '.json';

            Storage::disk('local')->put($path . $jsonTarget, json_encode($row->first(), TRUE));
            
            $row->delete();
        });
    }

}

Use class QueryBuilder on controller@destroy

....

    public function destroy($id)
    {
        $tableRelations = [
            'targets',
            'realisasis',
            'indikators',
            'sasarans',
            'pemangkus',
            'jabatans',
            'unit_kerjas',
            'unit_organisasis',
        ];

        $params = [
            'field' => 'opd_id',
            'value' => $id,
        ];

        $tableTarget = 'opds';

        QueryBuilder::deleteRelation($tableRelations, $params, $tableTarget);

        return response()->json('Success');
    }

....
FacebookTweetLinkedIn

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Recent Posts

  • Laravel & Datatables – Server Side Manualy
  • Linux – User Login Set Directory & Set Permission
  • Javascript Call Function From iFrame
  • Python – Create data dummy attendance
  • PHPWord Convert HTML + PDF

Categories

  • Apache
  • Database
  • Freeradius
  • Javascript
  • Mikrotik
  • Mysql
  • Networking
  • PHP
  • Postgresql
  • Programming
  • Python
  • Server
©2025 From Small to BIGGER | Built using WordPress and Responsive Blogily theme by Superb