РЕПЕТИТОР математика физика информатика
Для школьников и студентов. Подтягивание пробелов. ЦЭ, ЦТ, ОГЭ, ЕГЭ.
Идет набор на ЛЕТО. Жмите для подробностей:)
1336 of 1392 menu

Метод table

Метод table класса Command применяется для форматированного вывода данных в консоль в виде таблицы. Первым параметром передаётся массив заголовков столбцов, вторым - массив строк с данными. Метод автоматически выравнивает содержимое по ширине столбцов.

Синтаксис

<?php $this->table($headers, $rows); ?>

Пример

Давайте выведем список пользователей в виде таблицы:

<?php namespace AppConsoleCommands; use IlluminateConsoleCommand; use AppModelsUser; class ShowUsers extends Command { protected $signature = 'users:show'; protected $description = 'Show all users in table format'; public function handle() { $users = User::all(); $headers = ['ID', 'Name', 'Email', 'Created']; $rows = []; foreach ($users as $user) { $rows[] = [ $user->id, $user->name, $user->email, $user->created_at ]; } $this->table($headers, $rows); } } ?>

Результат выполнения команды:

+----+----------+---------------------+---------------------+ | ID | Name | Email | Created | +----+----------+---------------------+---------------------+ | 1 | user 1 | user1@example.com | 2026-01-01 10:00:00 | | 2 | user 2 | user2@example.com | 2026-01-02 11:30:00 | | 3 | user 3 | user3@example.com | 2026-01-03 14:20:00 | +----+----------+---------------------+---------------------+

Пример

Давайте выведем статистику по статьям, используя агрегированные данные:

<?php namespace AppConsoleCommands; use IlluminateConsoleCommand; use AppModelsArticle; class ArticleStats extends Command { protected $signature = 'article:stats'; protected $description = 'Display article statistics in table format'; public function handle() { $publishedCount = Article::where('status', 'published')->count(); $draftCount = Article::where('status', 'draft')->count(); $archivedCount = Article::where('status', 'archived')->count(); $totalCount = $publishedCount + $draftCount + $archivedCount; $headers = ['Status', 'Count', 'Percentage']; $rows = [ ['Published', $publishedCount, round(($publishedCount / $totalCount) * 100, 2) . '%'], ['Draft', $draftCount, round(($draftCount / $totalCount) * 100, 2) . '%'], ['Archived', $archivedCount, round(($archivedCount / $totalCount) * 100, 2) . '%'], ['Total', $totalCount, '100%'], ]; $this->table($headers, $rows); } } ?>

Результат выполнения кода:

+----------+-------+------------+ | Status | Count | Percentage | +----------+-------+------------+ | Published| 15 | 75% | | Draft | 3 | 15% | | Archived | 2 | 10% | | Total | 20 | 100% | +----------+-------+------------+

Пример

Давайте выведем таблицу с данными, переданными напрямую через аргументы команды:

<?php namespace AppConsoleCommands; use IlluminateConsoleCommand; class ShowProducts extends Command { protected $signature = 'products:show'; protected $description = 'Display product list in table format'; public function handle() { $headers = ['Product ID', 'Name', 'Price', 'Stock']; $rows = [ [101, 'Product A', '$ 25.00', 120], [102, 'Product B', '$ 35.50', 80], [103, 'Product C', '$ 15.75', 250], [104, 'Product D', '$ 42.30', 45], ]; $this->table($headers, $rows); $this->info('Products displayed successfully!'); } } ?>

Результат выполнения кода:

+------------+-----------+--------+-------+ | Product ID | Name | Price | Stock | +------------+-----------+--------+-------+ | 101 | Product A | $ 25.00| 120 | | 102 | Product B | $ 35.50| 80 | | 103 | Product C | $ 15.75| 250 | | 104 | Product D | $ 42.30| 45 | +------------+-----------+--------+-------+ Products displayed successfully!

Смотрите также

  • метод info,
    который выводит информационное сообщение в консоль
  • метод error,
    который выводит сообщение об ошибке в консоль
  • метод ask,
    который запрашивает ввод данных у пользователя
  • метод withProgressBar,
    который отображает индикатор выполнения
Мы используем cookie для работы сайта, аналитики и персонализации. Обработка данных происходит согласно Политике конфиденциальности.
принять все настроить отклонить