Zakaria Arrid

Under-the-hood LARAVEL tips


1. Dispatch after commit a transaction

   DB::transaction(function () {
        // Create a new user
        $user = User::create([
            'name' => 'John Doe',
            'email' => 'john@example.com',
            'password' => bcrypt('secret'),
        ]);

        // Create an order for the user
        $order = Order::create([
            'user_id' => $user->id,
            'product' => 'Product name',
            'quantity' => 1,
            'price' => 100,
        ]);

        // Optionally dispatch an event after committing 
        // the transaction as solution 1
        OrderCreated::dispatch($order)->afterCommit();
       
    });

or go to the queue.php config and enable after_commit

2. class_uses_recursive() Helper

class_uses_recursive() is used to retrieve all traits used by a given class

    if (! in_array(Batchable::class, class_uses_recursive($job))) {
        throw new RuntimeException(sprintf('Attempted to batch job [%s], 
        but it does not use the Batchable trait.', $job::class));
    }

or go to the queue.php config and enable after_commit

I will add under-the-hood functions gradually, day by day. .... by