DEV Community

tuandp
tuandp

Posted on

How to Run Any Script in Laravel

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();


Enter fullscreen mode Exit fullscreen mode

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;
}


Enter fullscreen mode Exit fullscreen mode

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"

_ide_helper_tinker

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)

Collapse
 
dr41d45 profile image
dr41d45

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...

Collapse
 
tuandp profile image
tuandp

PHPStorm has a similar plugin, but most of the time it isn't compatible with the latest upgrade 😉

Collapse
 
thimytrang_nguyen_6290b profile image
Jenny Nguyen

I will keep this handy article in mind. Thank you!