Search code examples
laravelauto

How to auto add new row to database according to the previous row in laravel every month?


    ID |  User  |    Date   
------------------------------   
 1     |   Ram  |    2019-1-1  
 2     |   Ram  |    2019-2-1  
 3     |   Ram  |    2019-3-1
 4     |  Shyam |    2019-4-1
 5     |  Shyam |    2019-5-1

Ram in ID 1 is entered in the begining. After that in every 1st day of the next months, the row 1 needs to be auto added into new row which is ID 2 here while updating the date as well as copying the user to the next month. And if the ram is edited as shown in 4th row to shyam, then starting the next month the edited value i.e shyam should start to be auto added to new row with changes to the date by 1month difference from old one as well. How can i accomplish this task?


Solution

  • You should create an Artisan command to get the previous row and create the next record based on that.

    php artisan make:command UpdateRecord
    

    Get the previous row like so:

    $model = YourModel::orderBy('date', 'DESC')->first();
    //Create new row here
    

    Then use the scheduler to run the command monthly in the App\Console\Kernel class:

    protected function schedule(Schedule $schedule) {
        $schedule->command(YourCommand::class)->monthly();
    }