Articles Snippets Projects

Write Multi Line Commands on Laravel Tinker

or any PsySH REPL Shell

August 8th ʼ22 2 days ago

3 min 559 words

TL; DR;

  • Put a backslash (\) character at the end.

  • After the unfinished PHP statements, you can just continue to write on multiple lines.

  • Use edit command on Tinker.


Laravel Tinker is a very lovely REPL for the Laravel Framework based on the PsySH Shell package.

Entering arbitrary code is very straightforward; you write the code and press Enter. By default, pressing Enter causes the Tinker REPL to read and evaluate the line that was entered.

Psy Shell v0.11.8 (PHP 8.1.10  cli) by Justin Hileman
>>> Hash::make('password');
=> "$2y$10$NCUGBewkGObNUffOSG2vturHwDSC1QBSsAaOv8kptcTh.7guU8cz."
>>> 

Things can become more complicated if you want to enter multi-line statements.

Entering Multi-Line Statements Using Backslash (\) Character

You can enter multi-line statements in the same way that Bash does by adding a backslash character at the end. The \ character allows you to continue the expression input across many lines; each line that is part of the input is started with .... The Tinker will continue to take multi-line inputs until a proper terminator or a parsing error is found.

Psy Shell v0.11.8 (PHP 8.1.10  cli) by Justin Hileman
>>> collect([ \
... 'a', \
... 'b', \
... 'c', \
... ])
=> Illuminate\Support\Collection {#3582
     all: [
       "a",
       "b",
       "c",
     ],
   }

>>> 

Beginning of an unfinished PHP Statements

The Tinker REPL will automatically switch to multi-line expression mode if the current line contains the beginning of an unfinished PHP statement. You could rewrite the previous example like this:

Psy Shell v0.11.8 (PHP 8.1.10  cli) by Justin Hileman
>>> collect([ \
... 'a',
... 'b',
... 'c',
... ])
=> Illuminate\Support\Collection {#3582
     all: [
       "a",
       "b",
       "c",
     ],
   }

>>> 

The edit Command

The edit command in the PsySH Shell launches an external editor and loads the generated code into the input buffer.

Psy Shell v0.11.8 (PHP 8.1.10  cli) by Justin Hileman
>>> edit 

After you've entered your multi-line statements, just save the temporary file and close the editor. You'll see that your code was appropriately inserted and executed.

You might change the default editor by creating an environment variable called EDITOR that points to your favorite editor's path.