How To Delete Records Older Than 7 Days In Laravel

  Dec 2023
  ITSolutionsGuides
  Category: Laravel
How To Delete Records Older Than 7 Days In Laravel

Hi Developers,

Lets see How To Delete Records Older Than 7 Days In Laravel. Sometimes we need to delete the records that are too old to increase the storage in the database. and also the old outdated records are no longer need for any analytics processes. It was done by fetching the records that are older than 7 days using the now()->subDays() and then we will delete the fetched 7 days old record using the delete(). So lets see How To Delete Records Older Than 7 Days In Laravel.

Learn to efficiently remove outdated records in Laravel using Eloquent. Harness the power of timestamps and Carbon library to filter and delete entries older than a week, ensuring a streamlined database.

Lets Start Coding

Lets create the controller using the following command,
php artisan make:controller PostController for detailed explanation about creating the controller view this link creating the controller

In this controller we are using the WhereDate() to fetch the data that are older than the 7 days before using the now()->subDays() where the number of days the records to be fetched should be entered here. And then lets delete the fetched record using delete()

<?php
     
namespace App\Http\Controllers;
     
use Illuminate\Http\Request;
use App\Models\Post;
     
class PostController extends Controller
{
    
    /**
     * Write code on Method
     *
     * @return response()
     */
    public function index(Request $request)
    {
   
        Post::whereDate('created_at', '<=', now()->subDays(7))->delete();
  
    }
}

We hope it helps everyone. Thanks for supporting ITSolutionsGuides and keep supporting us also follow us in social media platforms.

Subscribe for NewsLetter

Be the first to know about releases and tutorial news and solutions.

We care about your data in our privacy policy.

ITSolutionsGuides

ITSolutionsGuides was started mainly to provide good and quality web solutions for all the developers. We provide tutorials to support all the developers and also we try to provide solutions to the errors we face while coding.

Contact US

ITSolutionsGuides, provide users with an easy-to-use form to reach out for support or inquiries.

whatsapp  gmail  instagram-new--v1  facebook-circled  twitter-circled  linkedin  github  pinterest 

Copyright © 2023 - 2024 All rights reserved | ITSolutionsGuides