"Laravel: Real-time Application Data Issue Export Directly To A Slack Channel"
Tags: laravel, slack, webdev, ecommerce
Published: 2023-10-14 00:43:03

User interaction is vital for an application's success. With more users, chances of use case issues arises, thereby creating bad data in your application's db. Addressing these in real-time is crucial. Imagine if your app could proactively report defects or bad data to the team before clients notice. 

In this article, I'll show you how to integrate direct reporting to Slack via a Slack app, streamlining the process.

In this article, I will cover;

- Creating A Slack App

- Creating sample command that handles recognising failed payments with reference to a simple **E-commerce payment system** 

**Creating a slack app**
To get started, go to [Slack](https://api.slack.com/apps/) and click on the "Create New App" button. Then, select the first option as shown in the image below.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/s5bdsuqgxytu0vpvg618.png)


Enter the application name, choose a workspace, and then press the "Create App" button to save the form.


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/hoips57x2ztuqhnm9xlq.png)

After creating our app, choose the "Incoming Webhooks" option and toggle it on the next screen.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/lpras2igiz9j1o3d8y2b.png)

Navigate to the bottom of the page and select "Add New Webhook to Workspace." Then, on the following screen, pick a channel and click "Allow."


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/iazzj4t4um2pkjb61h4f.png)


Slack will generate a webhook URL. Copy it and paste it into your app's .env file as shown below.

```bash
FAILED_PAYMENT_SLACK_WEBHOOK_URL=https://hooks.slack.com/services/xxxxxxxxxx
```

**Creating sample command**

In Laravel, commands are custom, reusable scripts that perform specific tasks within the application. They can be executed via the command line interface (CLI) and are useful for automating tasks, such as database migrations, scheduled jobs, and custom operations.

In Laravel, custom commands are typically stored in the `app/Console/Commands` directory. You can create a new command using the Artisan CLI or by manually creating a new PHP file in that directory.

Here's an example of a basic command:

1. **Creating a Command**

You can create a command using Artisan. Open your terminal and run:

`php artisan make:command ExportFailedPayments
`
This will generate a new command file named `ExportFailedPayments.php` in the `app/Console/Commands` directory.

2. **Sample Command Code**

Open the generated `ExportFailedPayments.php` file and you'll find something like this:

```php
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Storage;

class ExportFailedPayments extends Command
{
    protected $signature = 'export:failed-payments';
    protected $description = 'Export failed payments to CSV and send to server';

    public function handle()
    {
        // Generate CSV data (replace this with your actual logic)
        $csvData = [
            ['order_id', 'payment_id', 'status'],
            [1, 101, 'failed'],
            [2, 102, 'failed'],
            // Add more rows as needed
        ];

        $csvFilePath = storage_path('app/failed_payments.csv');
        $file = fopen($csvFilePath, 'w');

        foreach ($csvData as $row) {
            fputcsv($file, $row);
        }

        fclose($file);

        $message = "Daily Failed Payment Report:\n
        File: <" . file_get_contents($csvFilePath) . "|Download CSV>";

        $data = [
            'text' => $message,
        ];

        Http::post(env('FAILED_PAYMENT_SLACK_WEBHOOK_URL'), $data); // Replace with your actual slack webhook url.


        // Clean up: Delete the local CSV file
        unlink($csvFilePath);
    }
}
```

3. **Using the Command**

You can now execute this command in the terminal using its signature:

```bash
php artisan export:failed-payments
```

This will trigger the `handle` method, and any logic you place there will be executed.

Remember, this is a basic example. Commands can perform a wide range of tasks, from database operations to complex data processing. But we are only referencing a failed payment export instance in this article.

In E-commerce, it is important to reconcile failed payment as early as possible, so in this article, I will show you how to create a cron job that schedules this command above to run as often as you want it to.

To schedule this command to run at e.g (5pm every day), you'll need to add an entry to your Laravel scheduler. Open the `App\Console\Kernel.php` file and add the following code to the `$commands` array:

```php
protected $commands = [
    // ... other commands ...
    Commands\ExportFailedPayments::class,
];
```

Next, in the `schedule` method of the same file, add the following line to schedule the command:

```php
protected function schedule(Schedule $schedule)
{
    // ... other scheduled tasks ...

    $schedule->command('export:failed-payments')
             ->dailyAt('17:00'); // This will run the command at 5:00 PM
}
```

Now, your `ExportFailedPayments` command will be scheduled to run at 5:00 PM every day. Make sure your server is correctly configured to handle Laravel's scheduled tasks (using cron or task scheduler depending on your server environment).


Below, you'll find an example of the report based on the focus of this article.


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/cqzw1bjg2thyl7tlwh9g.png)

I hope this was helpful. Thanks for dropping by!