how to modify a database from with laravel commands?

  database, kernel, laravel, php

I need to run a command that sorts through the users in my database but I can’t get it to work.
Here is my php file App>Console>Commands>SortUser.php :

<?php

namespace AppConsoleCommands;

use IlluminateConsoleCommand;

use AppModelsUser;

class SortUser extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'command:sortUser';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Command description';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        $users = User::all();
        $dateNow = new DateTime("now");
        foreach($users as $user){
            if($user['admin'] == 0){
                $lastConnexion = date_create($user["updated_at"]);
                $interval = date_diff($lastConnexion, $dateNow);
                if($interval->format('%a') >= 365){
                    // User::where('id', $user['id'])->delete();
                    User::where('id', $user['id'])->update([
                        'updated_at' => date("Y-m-d H:i:s")
                    ]);
                }
            }
        }
    }
}

I call this function from the Kernel.php file with the schedule function:

<?php

namespace AppConsole;

use IlluminateSupportFacadesArtisan;
use IlluminateConsoleSchedulingSchedule;
use IlluminateFoundationConsoleKernel as ConsoleKernel;

class Kernel extends ConsoleKernel
{
    /**
     * The Artisan commands provided by your application.
     *
     * @var array
     */
    protected $commands = [
        'AppConsoleCommandsSortUser',
    ];

    /**
     * Define the application's command schedule.
     *
     * @param  IlluminateConsoleSchedulingSchedule  $schedule
     * @return void
     */
    protected function schedule(Schedule $schedule)
    {
        $schedule->command('command:sortUser')->everyMinute();
    }

    /**
     * Register the commands for the application.
     *
     * @return void
     */
    protected function commands()
    {
        $this->load(__DIR__.'/Commands');

        require base_path('routes/console.php');
    }
}

It doesn’t work and I don’t even know how to see the errors.
So I need some tips to find the error message and to success to modify the database
Thank you

Source: Laravel

Leave a Reply