In Laravel, you can use the Eloquent ORM to delete records older than a certain number of days. Here’s an example of how you can delete all records older than 30 days:
To delete all records older than 30 days in Laravel, we’ll leverage the eloquent ORM (Object-Relational Mapping) and Laravel’s built-in features. This approach ensures simplicity and effectiveness in handling database operations.
First go to model and put below code
<?php
// Post.php
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
protected $table = 'posts';
// other model configurations
}
?>
Now that we have our model set up, we can construct a query to delete records older than 30 days. We’ll use the where
clause along with the delete
method.
use Carbon\Carbon;
public function deleteOldRecords()
{
$cutoffDate = Carbon::now()->subDays(30);
Post::where('created_at', '<', $cutoffDate)->delete();
return response()->json(['message' => 'Old records deleted successfully']);
}
This eloquent query efficiently deletes all records older than 30 days, taking advantage of Carbon for easy data manipulation.
In this tutorial, we delved into the process of deleting all records older than 30 days in Laravel 10. Leveraging eloquent models and the powerful Carbon library, we crafted a query that efficiently achieves the desired result.