Search code examples
mysqllaravelclone

Clone data from one to another database column in Laravel


I have two columns quantity and remaining_quantity in my stock table. I wanted to copy same data from quantity to remaining_quantity while doing a create function. Is there any function in Laravel for that?


Solution

  • You can do that by creating an observer.

    1- Create a folder called observers in you app folder.

    2- Create a file named MyModelObserver.php for example StockObserver.php.

    3- Prepare your class like the following:

    <?php
    namespace App\Observers;
    
    
    class StockObserver
    {
        //
    }
    

    Inside that class you can create creating, created, updated, updated, deleting, deleted, saving and saved methods. Which their jobs are obvious from their names. For more details see => https://laravel.com/docs/5.5/eloquent#events

    For example the following code will do something everytime an object of Stock model is created.

    <?php
    namespace App\Observers;
    
    
    use App\Stock;
    
    class StockObserver
    {
        public function created(Stock $stock)
        {
            $stock->remaining_quantity = $stock->quantity;
            $stock->save()
        }
    }
    

    But all these code won't be effective unless you observe that in the AppServiceProvide .. so in the boot method in AppServiceProvider write the following.

    \App\Stock::observe(\App\Observers\StockObserver::class);
    

    That's it .. Hope it helps.