0

I have just discovered the table rendering function in Laravel console command.
My project is built on Laravel 5.8, but even if there is an answer for more advanced versions it will be great to know.

I am looking for rendering a table with determined (or even better - limitted) column width. Something like:

$data = [
    ['John', 'The Curious Incident of the Dog in the Night-Time'],
    ['Rachel', 'The Catcher in the Rye']
];

// Code for columns width is missing
$this->table(['Name', 'Favorite book'], $data);

So the output will be:

+--------+-------------------------+
| Name   | Favorite book           |
+--------+-------------------------+
| John   | The Curious Incident... |
| Rachel | The Catcher in the Rye  |
+--------+-------------------------+

I saw that Symfony table (which laravel table is based on) has a setColumnWidths() function, but I cannot find any way to use it from the console command.

Does somebody know if it is possible?

guyaloni
  • 4,972
  • 5
  • 52
  • 92

1 Answers1

1

Unfortunately you cannot use setColumnWidths, because the table only supports table style and column style, as you can see here.

You can directly use the Symfony table, or simply create your word limit (via Str::limit) :

$size = 20;
$data = [
    ['John', Str::limit('The Curious Incident of the Dog in the Night-Time', $size)],
    ['Rachel', Str::limit('The Catcher in the Rye', $size)]
];

$this->table(['Name', 'Favorite book'], $data);
Wahyu Kristianto
  • 8,719
  • 6
  • 43
  • 68
  • Thanks, the approach you mentioned in your answer is the one I thought about. The problem is that for big data table it requieres me to iterate over all entries.... – guyaloni Feb 23 '22 at 09:58
  • 1
    I see. Maybe you can use [`SUBSTRING`](https://dev.mysql.com/doc/refman/8.0/en/string-functions.html#function_substring) from query – Wahyu Kristianto Feb 23 '22 at 10:02