Do you find yourself constantly opening up a terminal window to run Laravel's tinker console or other command-line scripts? With this simple code snippet, you can run any script directly from within your code editor or IDE.
First, make sure you have Laravel installed and have included the necessary autoload and bootstrap files at the top of your script. Then, add the following code into the file, let's call it _ide_helper_tinker.php
use Illuminate\Contracts\Console\Kernel;
require __DIR__ . '/vendor/autoload.php';
$app = require_once __DIR__ . '/bootstrap/app.php';
$kernel = $app->make(Kernel::class);
$kernel->bootstrap();
This code initializes Laravel's console kernel and boots up the application, allowing you to run any command-line script just as you would in a regular terminal window.
To run your script, simply add the code snippet above to your script and then call the script's command. For example:
use Illuminate\Contracts\Console\Kernel;
require __DIR__ . '/vendor/autoload.php';
$app = require_once __DIR__ . '/bootstrap/app.php';
$kernel = $app->make(Kernel::class);
$kernel->bootstrap();
// Run script command
$people = DB::table('people')->get();
foreach ($people as $person) {
echo $person->full_name . PHP_EOL;
}
If you are using PHPStorm or Jetbrain IDE, you can easily execute the script by right click on the file and selecting "Run PHP script"
That's it! Now you can run any command-line script from within your code editor or IDE, making it easier to debug and test your Laravel application.
One thing to keep in mind is that you may not want to track your script file changes using Git. To exclude your script file from Git tracking, add the file name to the .gitignore
file in the root directory of your project.
Top comments (3)
For Visual studio code users there is extension for same task (it eliminates this extra file, you just work with your code snipped):
marketplace.visualstudio.com/items...
PHPStorm has a similar plugin, but most of the time it isn't compatible with the latest upgrade 😉
I will keep this handy article in mind. Thank you!