Limited Time Offer!

For Less Than the Cost of a Starbucks Coffee, Access All DevOpsSchool Videos on YouTube Unlimitedly.
Master DevOps, SRE, DevSecOps Skills!

Enroll Now

How to Create Delete Command in Laravel ?

Creating a custom delete command in Laravel involves defining a new Artisan command class, specifying its signature, description, and implementing the logic to delete records based on your requirements. Here’s a step-by-step guide with explanations:

Benefits of Using this Delete Command

Creating a custom delete command in Laravel can offer several benefits, depending on the specific requirements and use cases of your application. Here are some potential benefits:

  1. Automation of Cleanup Tasks:
    • The delete command allows you to automate cleanup tasks by regularly removing records from your database that meet certain criteria.
    • This is particularly useful for removing outdated or unnecessary data, such as log entries, temporary records, or expired user sessions.
  2. Scheduled Data Maintenance:
    • By integrating the delete command into Laravel’s task scheduler, you can schedule it to run at specific intervals (e.g., daily, weekly, or monthly).
    • Scheduled data maintenance ensures that your database stays organized and optimized over time.
  3. Improved Performance:
    • Regularly deleting unnecessary records can help maintain optimal database performance by preventing the accumulation of large amounts of data.
    • Smaller, well-maintained databases generally perform better in terms of query speed and resource utilization.
  4. Resource Efficiency:
    • Cleaning up unnecessary data contributes to resource efficiency by reducing the storage space required for your database.
    • Smaller databases are easier to manage and may result in lower hosting costs.
  5. Data Privacy and Compliance:
    • For applications handling sensitive or personal data, the delete command can assist in complying with data privacy regulations.
    • Removing outdated or unnecessary user data helps maintain compliance with data protection laws.
  6. Database Consistency:
    • The delete command helps maintain database consistency by removing records that are no longer relevant or valid.
    • Consistent databases contribute to the overall reliability and integrity of your application.

Create command

php artisan make:command ClearDataCommand
Next to go to controller and put below code 
public function clearData()
    {
        Log::info('all delete section me hai');
        $data = [];
        $delteall_user = UserCount::truncate();
        $AddProfileGetting = AddProfileCount::truncate();
        $deleteOrgs = Userorganisation::truncate();
        $deleteOrganisations = Organisation::truncate();
        $delte_projects = Projects::truncate();
        $AddurlCount = AddurlCount::truncate();
        $getting_keyword = Keyword_count::truncate();
        $TeamRating_count = TeamRating::truncate();
        $WebRankCount = WebRankCount::truncate();
        $pageranking = pageranking::truncate();
        $socialrank = socialrank::truncate();
        $PhonenumberCount = PhonenumberCount::truncate();
        $Mywebaccesstoken = Mywebaccesstoken::truncate();
        $Mywebaccess = Mywebaccess::truncate();
        $EmailCount = EmailCount::truncate();
        // $SeoPanel =SeoPanel::truncate();
        $TasksBoard = TasksBoard::truncate();
        $Interval = Interval::truncate();
        $response = [
            'success' => true,
            'data' => $data,
            'message' => 'Data retrieved successfully.',
        ];
        return response()->json($response, 200);
    }

Next go to ClearDataCommand.php and put below code

<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Log;
use App\Http\Controllers\Api\AccountAdminController;
class ClearDataCommand extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'clear:data';
    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Clears data using the clearData function';
    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        Log::info("clear data me in kiye hai");
        $accountAdminController = new AccountAdminController();
        $response = $accountAdminController->clearData();
        $this->info('Account data cleared successfully.');
    }
}

Next go to console   ->   ClearDataCommand.php

<?php
namespace App\Console;
use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Foundation\Console\Kernel as ConsoleKernel;
class Kernel extends ConsoleKernel
{
    /**
     * Define the application's command schedule.
     *
     * @param  \Illuminate\Console\Scheduling\Schedule  $schedule
     * @return void
     */
    protected function schedule(Schedule $schedule)
    {
        // $schedule->command('inspire')->hourly();
    }
    /**
     * Register the commands for the application.
     *
     * @return void
     */
    protected function commands()
    {
        $this->load(__DIR__.'/Commands');
        require base_path('routes/console.php');
    }
}

Next to run below command

php artisan clear:data

Lets check to database.

I hope its helpfull for you šŸ‘šŸ‘.

Hi I am Amit Kumar Thakur Experienced as s Software Developer with a demonstrated history of working in the information technology and services industry. Skilled in HTML, CSS, Bootstrap4, PHP, Laravel-9 , REST API,FB API,Google API, Youtube Api, Bitbucket,Github,Linux and jQuery. Strong engineering professional focused in Computer/Information Technology Administration and Management. Currently my profile is to Software Developer, analyze the requirement, creating frame for web application, coding and maintenance.

Related Posts

How to Crawl any website Meta Title and Meta Description in Laravel ?

1st step install below package. Next to create Controller First go to route and put below code Next go to controller and put below code Next go…

SQLSTATE[HY000] [2002] No such file or directory (Connection: mysql, SQL: insert into `oauth_clients` (`user_id`, `name`, `secret`

In this tutorial i’m going to solve the error SQLSTATE[HY000] [2002] No such file or directory (Connection: mysql, SQL: insert into oauth_clients (user_id, name, secret Error :-…

Top 20 Laravel Interview Question in 2024

In this tutorial im going share interview experience For laravel developer. A list of top frequently asked Laravel Interview Questions and answers are given below. Q #1) What is…

How to Get Google Analytics API key ?

In this tutorial we’re going to share how to get the google Analytics API key. I have shared in very easy way. First go enable Google analytics…

Youtube Subscriber Count in ReactJs

In this tutorial iā€™m going to learn how to count YouTube Subsribers count, views count as well, as define below. In order to install your app, first…

How to Disable Laravel’s Eloquent timestamps in laravel ?

In this tutorial we’re going to share how to disable the automatic created_at and updated_at timestamps in Laravel’s Eloquent models, along with explanations of different scenarios: 1st…

0 0 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x