Search code examples
laravellaravel-query-builder

How to delete all the data from a table after 5 seconds using Laravel Query Builder?


I have this query

$data = DB::table('incidencias')
    ->select(DB::raw("STR_TO_DATE(fecha_notif, '%d/%m/%Y %H:%i:%s') as time"))
    ->get();

    $data = json_decode(json_encode($data, true), true);

    DB::table('incidencia_tiempo')->insert($data);

I would like to delete all the data from the table only one time after run the query.... for example if I refresh, the data will be deleted after 5 seconds, with one time is enough... is it posible?


Solution

  • To delete all data in a table, it's as simple as doing

    DB::table('incidencias')->truncate()
    

    or

    DB::table('incidencias')->delete();
    

    Update

    If you want to delete the data after 5 seconds have passed, then you can just do:

    sleep(5)
    DB::table('incidencias')->delete();
    

    Refresh using Javascript

    Your controller:

    public function deleteAll()
    {
        DB::table('incidencias')->truncate();
    
        if (request()->ajax()) {
            return response()->json(['success' => true]);
        }
        
        return back(); // if not ajax...
    }
    

    Your HTML

    // For example, deleting it all every 5 seconds AFTER the delete button is pressed
    <button id="delete">Delete all</button>
    
    <script>
        $('#delete').click(function () {
            // in this case start deleting when you click this delete button only once..
            startDeleting();
        });
    
        // the actual code that does the GET request to the URL every 5 seconds
        function startDeleting() {
            setInterval(function () {
                // Submit as post/get depending on your route config.
                $.ajax({
                    url: "/your-url-to-controller", success: function (result) {
                        // what to do if we get success (if you wanna do anything)
                        console.log(result);
                    }
                });
            }, 5000); // time in milliseconds
        }
    </script>