Home > Enterprise >  How to create a functions in laravel which would be always running while the server runs [Solved]
How to create a functions in laravel which would be always running while the server runs [Solved]

Time:01-08

So, I want to make a function which will keep updating my product inventory and I need the function to be running continuously as long as the server or application would be running.....

Thanks In Advance!!!

My Expectations:

while (true)
{
    $product->quantity  = $updated
    // This would be running continuously     
}

CodePudding user response:

Ok, after some help I got the solution to use laravel commands with task scheduling with the least available running of every one minute.

First, Make a new command:

php artisan make:command ProductQuantityUpdate // Command Name

Second, Locate the ProductQuantityUpdate.php at App\Console\Commands\ProductQuantityUpdate.php and type your desired function in the handle():

Note: You can also edit the command name & description through the:

/**
 * The name and signature of the console command.
 *
 * @var string
 */
protected $signature = 'productquantity:update';

/**
 * The console command description.
 *
 * @var string
 */
protected $description = 'Update Product Quantity!';

Full Code [App\Console\Commands\ProductQuantityUpdate.php]:

<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;

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

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Update Product Quantity!';

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        $pro = \App\Models\Product::get();
        foreach($pro as $product)
        {
            $qty = 0;
            $selecteds = \App\Models\AttributeValue::where('product_id', $product->id)->get();
            if($selecteds->count() > 0)
            {
                foreach($selecteds as $select)
                {
                    $qty  = $select->quantity;
                }
                $product->quantity = $qty;
                $product->save();
            }
        }

        $this->info('Product Quantity Updated!');

        return Command::SUCCESS;
    }
}

Third, Go to App\Console\Kernel.php and add the command, and schedule function:

protected $commands = [
        Commands\ProductQuantityUpdate::class,
    ];

protected function schedule(Schedule $schedule)
{
    $schedule->command('productquantity:update')->everyMinute(); 
    // Check the documentation for available timings!
}

To check your command, type this in the console:

php artisan list

To check your schedule, type this in the console:

php artisan schedule:list

Documentation that also helped me : Couldways documentation

  • Related