> ## Documentation Index
> Fetch the complete documentation index at: https://kawax.biz/llms.txt
> Use this file to discover all available pages before exploring further.

# Tutorial - Laravel Console Starter

> Anleitung zum Aufbau einer Konsolen-Anwendung mit dem Laravel Console Starter. Sie lernen Kommandos zu erstellen, Scheduling per GitHub Actions, das Senden von Benachrichtigungen und praktische Anwendungsbeispiele.

## Einführung

In diesem Tutorial bauen Sie mit `revolution/laravel-console-starter` eine Laravel-Anwendung mit eigenen Artisan-Kommandos auf.

Vorteile dieses Starter-Kits:

* **Schnelle Einrichtung** – Ohne komplizierte Konfiguration können Sie sofort mit der Entwicklung von Konsolen-Anwendungen beginnen.
* **Laravel-Ökosystem** – Sie können Laravels reichhaltige Funktionen wie Task-Scheduling, Datenbank und Notifications nutzen.
* **Artisan-Kommandos** – Über das leistungsfähige Artisan-System von Laravel erstellen und verwalten Sie eigene Kommandos einfach.
* **Testbarkeit** – Sie können Tests für Ihre Kommandos mit dem Test-Framework von Laravel schreiben.

## Voraussetzungen

Installieren Sie die folgende Software.

* PHP `^8.3`
* Composer ([https://getcomposer.org/](https://getcomposer.org/))
* Laravel Installer (`composer global require laravel/installer`)

## Projekt einrichten

<Steps>
  <Step title="Neues Projekt erstellen">
    Führen Sie im Terminal folgenden Befehl aus.

    ```bash theme={null}
    laravel new my-app --using=revolution/laravel-console-starter --no-interaction
    ```

    Das Verzeichnis `my-app` wird angelegt und die Grundstruktur der Konsolen-Anwendung eingerichtet.

    Automatisch werden bei der Installation ausgeführt:

    * Erzeugung der `.env`-Datei aus `.env.example`
    * Setzen des Application Keys per `php artisan key:generate`

    Wichtige Verzeichnisstruktur:

    ```
    my-app/
    ├── app/Console/Commands/   # Eigene Kommandos ablegen
    ├── .github/workflows/
    │   └── cron.yml            # Beispiel für GitHub-Actions-Schedule
    ├── config/                 # Anwendungskonfiguration
    └── routes/console.php      # Registrierung der Kommandos
    ```
  </Step>

  <Step title="Umgebungseinstellungen prüfen">
    Standardmäßig ist der Mail-Versand auf Log-Ausgabe eingestellt (`MAIL_MAILER=log`).

    Wenn Sie tatsächliche Mails versenden möchten, konfigurieren Sie in `.env` einen Dienst wie Mailgun, Postmark oder SES.
  </Step>
</Steps>

## Konsolen-Kommando erstellen

<Steps>
  <Step title="Kommando generieren">
    Erstellen Sie mit dem Artisan-Kommando `make:command` ein neues Kommando.

    ```bash theme={null}
    php artisan make:command YourCommandName --command=your:command
    ```

    * `YourCommandName` – Klassenname des zu erstellenden Kommandos (z. B. `SendDailyReport`)
    * `your:command` – Aufrufname des Kommandos (z. B. `report:send-daily`)

    Es wird `app/Console/Commands/YourCommandName.php` erzeugt.
  </Step>

  <Step title="Kommando implementieren">
    Bearbeiten Sie die erzeugte Datei und implementieren Sie die Logik. Das folgende Beispiel zeigt ein Hello-World-Kommando.

    ```php theme={null}
    <?php

    namespace App\Console\Commands;

    use Illuminate\Console\Command;
    use Illuminate\Support\Facades\Log;

    class HelloWorldCommand extends Command
    {
        protected $signature = 'hello:world';
        protected $description = 'Displays a hello world message in the log';

        public function handle(): int
        {
            Log::info('Hello, World from Artisan Command!');
            $this->info('Hello, World message has been logged.');
            return Command::SUCCESS;
        }
    }
    ```

    Über `$signature` definieren Sie den Aufrufnamen des Kommandos, in der Methode `handle()` schreiben Sie die Logik.
  </Step>

  <Step title="Kommando ausführen">
    ```bash theme={null}
    php artisan hello:world
    ```

    Nach der Ausführung wird eine Meldung in `storage/logs/laravel.log` und auf der Konsole ausgegeben.
  </Step>
</Steps>

## Task-Scheduling mit GitHub Actions

Mit GitHub Actions können Sie Kommandos regelmäßig ausführen, ohne einen Cronjob auf einem Server einrichten zu müssen.

<Steps>
  <Step title="Workflow-Datei prüfen">
    Im Starter-Kit ist die Datei `.github/workflows/cron.yml` bereits vorkonfiguriert enthalten.

    ```yaml theme={null}
    name: cron

    on:
      schedule:
        - cron: '0 0 * * *'  # Täglich 00:00 UTC

    jobs:
      cron:
        runs-on: ubuntu-latest
        steps:
          - uses: actions/checkout@v6
          - uses: shivammathur/setup-php@v2
            with:
              php-version: 8.5
              coverage: none
          - run: composer install --no-dev -q
          - run: cp .env.example .env
          - run: php artisan key:generate
          - run: php artisan inspire
    ```
  </Step>

  <Step title="Kommando anpassen">
    Ersetzen Sie `php artisan inspire` durch Ihr eigenes Kommando.

    ```yaml theme={null}
    - name: Run Command
      run: php artisan your:command
    ```

    Für mehrere Kommandos:

    ```yaml theme={null}
    - name: Run Commands
      run: |
        php artisan first:command
        php artisan second:command
    ```
  </Step>

  <Step title="Zeitplan anpassen">
    Passen Sie den `cron`-Ausdruck an, um die Ausführungshäufigkeit festzulegen.

    | cron-Ausdruck | Ausführungszeitpunkt  |
    | ------------- | --------------------- |
    | `0 0 * * *`   | Täglich 00:00 UTC     |
    | `0 */6 * * *` | Alle 6 Stunden        |
    | `0 0 * * 1`   | Jeden Montag um 00:00 |
  </Step>

  <Step title="Vertrauliche Daten über Secrets verwalten">
    Vertrauliche Informationen wie API-Keys und Passwörter verwalten Sie über die GitHub-Repository-Secrets.

    Fügen Sie unter **Settings > Secrets and variables > Actions** im GitHub-Repository Secrets hinzu und referenzieren Sie sie im Workflow.

    ```yaml theme={null}
    - name: Run Command with Secrets
      run: php artisan your:command
      env:
        API_KEY: ${{ secrets.API_KEY }}
        DB_PASSWORD: ${{ secrets.DATABASE_PASSWORD }}
    ```
  </Step>
</Steps>

## Notification-Funktionen

Sie können die Ergebnisse oder Fehler eines Kommandos per Mail, Slack usw. benachrichtigen.

<Steps>
  <Step title="Notification-Klasse erstellen">
    ```bash theme={null}
    php artisan make:notification TaskCompleted
    ```

    Es wird `app/Notifications/TaskCompleted.php` erzeugt.
  </Step>

  <Step title="Notification-Kanal konfigurieren">
    Veröffentlichen Sie bei Bedarf die Konfigurationsdateien.

    ```bash theme={null}
    php artisan config:publish mail
    php artisan config:publish services
    ```
  </Step>

  <Step title="Aus dem Kommando eine Benachrichtigung versenden">
    ```php theme={null}
    <?php

    namespace App\Console\Commands;

    use App\Notifications\TaskCompleted;
    use Illuminate\Console\Command;
    use Illuminate\Support\Facades\Notification;

    class ProcessDataCommand extends Command
    {
        protected $signature = 'data:process';
        protected $description = 'Daten verarbeiten und nach Abschluss eine Benachrichtigung senden';

        public function handle()
        {
            $this->info('Daten werden verarbeitet...');

            // Verarbeitungslogik...

            Notification::route('mail', 'admin@example.com')
                ->notify(new TaskCompleted('Datenverarbeitung erfolgreich abgeschlossen'));

            return Command::SUCCESS;
        }
    }
    ```
  </Step>
</Steps>

<Info>
  Details siehe [Laravel-Notification-Dokumentation](https://laravel.com/docs/notifications).
</Info>

## Praktische Anwendungsbeispiele

### Beispiel 1: Verfügbarkeitsüberwachung von Websites mit Slack-Alerts

Ein Kommando, das prüft, ob Websites online sind, und bei Problemen einen Alert an Slack sendet.

<Steps>
  <Step title="Slack-Notification-Kanal installieren">
    ```bash theme={null}
    composer require laravel/slack-notification-channel
    ```
  </Step>

  <Step title="Kommando und Notification erstellen">
    ```bash theme={null}
    php artisan make:command MonitorWebsites --command=monitor:websites
    php artisan make:notification WebsiteDown
    ```
  </Step>

  <Step title="Slack konfigurieren">
    ```bash theme={null}
    php artisan config:publish services
    ```

    Fügen Sie in `.env` die Slack-Webhook-URL hinzu.

    ```
    SLACK_WEBHOOK_URL=https://hooks.slack.com/services/YOUR/WEBHOOK/URL
    ```

    Aktualisieren Sie `config/services.php`.

    ```php theme={null}
    'slack' => [
        'webhook_url' => env('SLACK_WEBHOOK_URL'),
    ],
    ```
  </Step>

  <Step title="Notification implementieren">
    Bearbeiten Sie `app/Notifications/WebsiteDown.php`.

    ```php theme={null}
    <?php

    namespace App\Notifications;

    use Illuminate\Notifications\Messages\SlackMessage;
    use Illuminate\Notifications\Notification;

    class WebsiteDown extends Notification
    {
        public function __construct(
            protected string $website,
            protected string $error,
        ) {}

        public function via($notifiable): array
        {
            return ['slack'];
        }

        public function toSlack($notifiable): SlackMessage
        {
            return (new SlackMessage)
                ->error()
                ->content('Website-Ausfall-Alert!')
                ->attachment(function ($attachment) {
                    $attachment->title($this->website)
                               ->content("Fehler: {$this->error}")
                               ->timestamp(now());
                });
        }
    }
    ```
  </Step>

  <Step title="Kommando implementieren">
    Bearbeiten Sie `app/Console/Commands/MonitorWebsites.php`.

    ```php theme={null}
    <?php

    namespace App\Console\Commands;

    use App\Notifications\WebsiteDown;
    use Illuminate\Console\Command;
    use Illuminate\Support\Facades\Http;
    use Illuminate\Support\Facades\Log;
    use Illuminate\Support\Facades\Notification;

    class MonitorWebsites extends Command
    {
        protected $signature = 'monitor:websites {--timeout=10}';
        protected $description = 'Websites auf Erreichbarkeit prüfen und bei Ausfall Slack-Alert senden';

        protected array $websites = [
            'https://example.com',
            'https://yourwebsite.com',
        ];

        public function handle(): int
        {
            $timeout = (int) $this->option('timeout');
            $webhookUrl = config('services.slack.webhook_url');
            $hasErrors = false;

            foreach ($this->websites as $website) {
                try {
                    $response = Http::timeout($timeout)->get($website);
                    if ($response->successful()) {
                        $this->info("{$website}: online ✓");
                    } else {
                        $error = "HTTP-Status: " . $response->status();
                        $this->error("{$website}: ausgefallen ({$error})");
                        Notification::route('slack', $webhookUrl)
                            ->notify(new WebsiteDown($website, $error));
                        $hasErrors = true;
                    }
                } catch (\Exception $e) {
                    $this->error("{$website}: Fehler ({$e->getMessage()})");
                    Log::error("Prüfung von {$website} fehlgeschlagen", ['error' => $e->getMessage()]);
                    Notification::route('slack', $webhookUrl)
                        ->notify(new WebsiteDown($website, $e->getMessage()));
                    $hasErrors = true;
                }
            }

            return $hasErrors ? Command::FAILURE : Command::SUCCESS;
        }
    }
    ```
  </Step>

  <Step title="Schedule mit GitHub Actions einrichten">
    Aktualisieren Sie `.github/workflows/cron.yml`.

    ```yaml theme={null}
    name: Website Monitoring

    on:
      schedule:
        - cron: '*/15 * * * *'  # Alle 15 Minuten ausführen

    jobs:
      monitor:
        runs-on: ubuntu-latest
        steps:
          - uses: actions/checkout@v6
          - uses: shivammathur/setup-php@v2
            with:
              php-version: 8.5
          - run: composer install --no-dev -q
          - run: cp .env.example .env
          - run: php artisan key:generate
          - name: Monitor Websites
            run: php artisan monitor:websites
            env:
              SLACK_WEBHOOK_URL: ${{ secrets.SLACK_WEBHOOK_URL }}
    ```
  </Step>
</Steps>

### Beispiel 2: Kryptoportfolio-Update mit Discord-Benachrichtigung

Ein Kommando, das über die CoinGecko-API Kryptowährungskurse abruft und Updates per Discord-Webhook sendet.

<Steps>
  <Step title="Discord-Notification-Kanal installieren">
    ```bash theme={null}
    composer require revolution/laravel-notification-discord-webhook
    ```
  </Step>

  <Step title="Kommando und Notification erstellen">
    ```bash theme={null}
    php artisan make:command UpdateCryptoPortfolio --command=crypto:portfolio
    php artisan make:notification CryptoPortfolioUpdate
    ```
  </Step>

  <Step title="Discord konfigurieren">
    Fügen Sie in `.env` die Discord-Webhook-URL hinzu.

    ```
    DISCORD_WEBHOOK=https://discord.com/api/webhooks/YOUR/WEBHOOK
    ```

    Aktualisieren Sie `config/services.php`.

    ```php theme={null}
    'discord' => [
        'webhook' => env('DISCORD_WEBHOOK'),
    ],
    ```
  </Step>

  <Step title="Kommando implementieren und ausführen">
    Für die Detail-Implementierung siehe das [Tutorial im GitHub-Repository](https://github.com/invokable/laravel-console-starter/blob/main/docs/tutorial_ja.md).

    ```bash theme={null}
    php artisan crypto:portfolio
    ```
  </Step>
</Steps>

### Beispiel 3: Website-Content-Scraping mit Mail-Benachrichtigung

Ein Kommando, das Inhalte von einer Website scrapt und das Ergebnis per Mail versendet.

<Steps>
  <Step title="Kommando und Notification erstellen">
    ```bash theme={null}
    php artisan make:command WebScraper --command=scrape:website
    php artisan make:notification ScrapingCompleted
    ```
  </Step>

  <Step title="Mail konfigurieren">
    ```bash theme={null}
    php artisan config:publish mail
    ```

    Fügen Sie die Mail-Konfiguration in `.env` hinzu.

    ```
    MAIL_MAILER=smtp
    MAIL_HOST=smtp.mailtrap.io
    MAIL_PORT=2525
    MAIL_USERNAME=your_username
    MAIL_PASSWORD=your_password
    MAIL_ENCRYPTION=tls
    MAIL_FROM_ADDRESS=your-app@example.com
    MAIL_FROM_NAME="${APP_NAME}"
    ```
  </Step>

  <Step title="Kommando implementieren und ausführen">
    ```php theme={null}
    protected $signature = 'scrape:website {--url=https://example.com} {--email=admin@example.com}';

    public function handle(): int
    {
        $url = $this->option('url');
        $email = $this->option('email');

        $response = Http::timeout(30)->get($url);

        // Inhalte verarbeiten und Benachrichtigung senden...
        Notification::route('mail', $email)
            ->notify(new ScrapingCompleted(true, $url, $title, $content));

        return Command::SUCCESS;
    }
    ```

    ```bash theme={null}
    php artisan scrape:website --email=admin@example.com
    ```
  </Step>
</Steps>

## Nächste Schritte

Sie haben die Grundlagen einer Laravel-Konsolen-Anwendung mit `revolution/laravel-console-starter` kennengelernt.

Zum weiteren Vertiefen:

* **Laravel-Dokumentation erkunden** – In der [offiziellen Laravel-Dokumentation](https://laravel.com/docs) finden Sie Funktionen, mit denen Sie Ihre Konsolen-Anwendung erweitern können.
* **Tests implementieren** – Schreiben Sie mit dem Test-Framework von Laravel Tests für Ihre Kommandos, um Verlässlichkeit zu gewährleisten.
* **Paket-Entwicklung erwägen** – Wenn Sie in mehreren Projekten ähnliche Kommandos benötigen, ziehen Sie in Betracht, sie als wiederverwendbares Laravel-Paket zu veröffentlichen.
* **Auf dem Laufenden bleiben** – Folgen Sie [Laravel News](https://laravel-news.com/) und dem offiziellen Blog, um Best Practices im Blick zu behalten.


## Related topics

- [Laravel Console Starter](/de/packages/laravel-console-starter/index.md)
- [Starter Kits](/de/starter-kits.md)
- [Ein Laravel-Starter-Kit erstellen](/de/advanced/starter-kit-creation.md)
- [Bot-Tutorial - Laravel Bluesky](/de/packages/laravel-bluesky/bot-tutorial.md)
- [Installation](/de/installation.md)
