Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

ojthejuice's avatar

One time scripts with access to app namespaces

Can someone please advise how to create and on time script that has access to all namespaces in my app. I dont want to use artisan console commands. Just a "php myscript.php". I also want to be able to debug it in phpstorm.

0 likes
30 replies
jimmck's avatar

Add this to your script.

require dirname(__DIR__) . '/vendor/autoload.php';
require dirname(__DIR__) . '/bootstrap/app.php';

You can access Laravel and your stuff from your custom scripts.

ojthejuice's avatar

Note: Using a homestead environment.

My Thoughts: Seems as if the db connection is null.

Okay this is what I have, and I get a PHP Fatal error: Call to a member function connection() on a non-object in .../vendor/laravel/framework/src/Illuminate/Database/Eloquent/Model.php on line 3224 . . . . PHP 12. Illuminate\Database\Eloquent\Model::resolveConnection($connection = uninitialized) .../vendor/laravel/framework/src/Illuminate/Database/Eloquent/Model.php:3190

<?php
namespace PATH\TO\MY\SCRIPT;

require dirname(__FILE__) . '../../../../bootstrap/app.php';
require dirname(__FILE__) . '../../../../vendor/autoload.php';

use PATH\TO\DESCRIPTION as Description;

class NameOfScript
{
    private $array = [
        'value',
    .
    .
    .
    ];

    public function addGeneralInformation() {
        foreach($this->$array as $data) {
            $description = Description::where('description', '=', $data)->first();
            if ($description != null) {
               $description->description = ucwords($data);
            } else {
                Description::create(['description' => $data]);
            }
        }
    }
}

$job = new NameOfScript();
$job->addGeneralInformation();
jimmck's avatar

Where is the script file located in relation to your Laravel project dir? Why are you using FILE? Need to seem how you are setting things up. i.e. actual directory structure.

ojthejuice's avatar

I have a folder in the app dir. The full path is app/Application_Helpers/Foo/FooBar/NameOfScript.php

ojthejuice's avatar

The script is not in the root directory. Im I missing something. Does the order matter?

jimmck's avatar

The order does matter. Create a bin directory under laravel project directory.

Create a new file in your bin directory. Add my examples exactly. Don't namespace the file.

put in your code. lets go from there.

ojthejuice's avatar

I created a ProjectRoot/bin/ScriptName.php. And inside in removed namespace and put

require dirname(__DIR__) . '/vendor/autoload.php';
require dirname(__DIR__) . '/bootstrap/app.php';

sames error as above

Okay this is what I have, and I get a PHP Fatal error: Call to a member function connection() on a non-object in .../vendor/laravel/framework/src/Illuminate/Database/Eloquent/Model.php on line 3224 . . . . PHP 12. Illuminate\Database\Eloquent\Model::resolveConnection($connection = uninitialized) .../vendor/laravel/framework/src/Illuminate/Database/Eloquent/Model.php:3190

jimmck's avatar

post your script put it in between 3 back ticks ```

ojthejuice's avatar
<?php
require dirname(__DIR__) . '/vendor/autoload.php';
require dirname(__DIR__) . '/bootstrap/app.php';

use MyApp\Meal\Description as Description;

class PopulateMealDescriptions
{
    private $generalFoods = [
        'asparagus',
        'apples',
        'Zucchini',
    ];

    public function __construct()
    {

    }

    public function addGeneralFoods() {
        foreach($this->generalFoods as $food) {
            $description = Description::where('description', '=', $food)->first();
            if ($description != null) {
               $description->description = ucfirst($food);
            } else {
                Description::create(['description' => $food]);
            }
        }
    }
}

$job = new PopulateMealDescriptions();
$job->addGeneralFoods();

Error

/usr/local/php5-5.5.15-20140809-134316/bin/php -dxdebug.remote_enable=1 -dxdebug.remote_mode=req -dxdebug.remote_port=9000 -dxdebug.remote_host=127.0.0.1 /Users/James/...MyApp/bin/PopulateMealDescriptionsTable.php
PHP Fatal error:  Call to a member function connection() on a non-object in /Users/James/...../vendor/laravel/framework/src/Illuminate/Database/Eloquent/Model.php on line 3224

PHP Stack trace:
PHP   1. {main}() /Users/James/....bin/PopulateMealDescriptionsTable.php:0
Fatal error: Call to a member function connection() on a non-object in /Users/James/..../vendor/laravel/framework/src/Illuminate/Database/Eloquent/Model.php on line 3224
PHP   2. PopulateMealDescriptions->addGeneralFoods() /Users/James/..../bin/PopulateMealDescriptionsTable.php:159

Call Stack:
PHP   3. MyApp\Meal\Description::where(*uninitialized*, *uninitialized*, *uninitialized*) /Users/James/.../bin/PopulateMealDescriptionsTable.php:148
.
.
.
PHP  12. Illuminate\Database\Eloquent\Model::resolveConnection($connection = *uninitialized*) /Users/James/.../vendor/laravel/framework/src/Illuminate/Database/Eloquent/Model.php:3190
    0.1383    3508112  12. Illuminate\Database\Eloquent\Model::resolveConnection(???) /Users/James/.../vendor/laravel/framework/src/Illuminate/Database/Eloquent/Model.php:3190


Process finished with exit code 255

jimmck's avatar

Looks like the Facades are not being initialized and/or config file is not being read. I was getting the bare minimum. I don't use Eloquent. Gonna have see what is missing Laravel build the world. Calling App returns $app. That should be visible in your script. You may need to access things via that. Just a guess? Have you got this setup in PHPStorm. That will help debug what is missing and more importantly what is available i your environment.

jimmck's avatar

Humbly recommend to shorten your example script till you get sorted out a little. 2 of each is more than enough.

ojthejuice's avatar

Can I do something like a composer update or optimize or reload or something. kind of new to composer.

jimmck's avatar

Ahh no. Do you have a running Laravel app yet?

ojthejuice's avatar

Yeah, homestead. I cut the code and put it in a controller and setup a route and it works fine. ran it from a browser it works fine.

jimmck's avatar

Got it. So you would like to test/play without needing to go the browser route? Specifically model stuff? Gotta see what is not setup. Can debug in PHPStorm? Also you have Tinker, never tried it, but you may find it useful.

willvincent's avatar

I'm not entirely sure why you want to avoid artisan, but I think you can mostly do so but still use it and save yourself a bunch of headache by adding a 'script' command that lets you fire scripts from an already bootstrapped environment.

For example:

<?php namespace App\Console\Commands;

use Illuminate\Console\Command;

class Script extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'script 
                            {filename : path/filename.php of script to run relative to project root} 
                            {args?* : Optional args to pass to script}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Runs a script inside a bootstrapped laravel environment.';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        // Make $args (if any) available to the file being included
        $args = $this->argument('args');

        // include the script file to run
        require($this->argument('filename'));
    }
}

Then, suppose you had a script file that looked like this:

<?php

foreach ($args as $arg) {
    var_dump($arg::all()->toArray());
}

You could execute: php artisan script filename.php App\\User App\\Task

Which in turn would vardump the results of calling App\User::all()->toArray() and App\Task::all()->toArray() from within laravel.

If you wanted a class, or multiple classes in your script that'd be fine, just include something outside of the classes that will run by default to instantiate your class/etc.

1 like
ojthejuice's avatar

But how do I debug it. I created an artisan command the other day. I like it but, honestly I dont know how to debug it. That probably a simple question, lol.

I guess i could debug artisan and set breakpoints in the command script.

ojthejuice's avatar

Yeah, i was trying to avoid all of that. I had the most trouble setting that stuff up with: different phpstorm, php versions, and different environments. Its just a hassle. I really wanted to find out a way to do one off scripts, setup a debug configuration in phpstorm and done with it. I have another idea that knowing this would be handy down the road. Thanks, I guess the command script will have to work for now.

willvincent's avatar

It sounds like you want everything to "just work" without doing the work to get it set up that way. Life tends to not be that way. ;)

ojthejuice's avatar

NO, It sounds like. I wanted to do it a way YOU ALSO don't know how to do it. If you don't know, you don't know. I posted this for help. I really appreciate your comments but the last one was unnecessary.

jimmck's avatar

I had to get fairly comfortable with Laravel to get my scripts to run and debug. I had to read quite a bit of Laravel code to get those scripts to fit my needs. As I said, I don't use Eloquent, but the parts of the framework I interact with took research. I will tell you do use PHPStorm meaningfully will take some effort regardless of framework. And thanks @willvincent for the Command example a good idea to keep in mind.

1 like
jimmck's avatar

@ojthejuice Dude! That was totally uncalled for. People are, well, were trying to help you.

ojthejuice's avatar

I know your trying to help, and i give you much thanks. But as I mentioned earlier. I was trying to avoid the command scripts. I believe trying to convince me to use them and giving a life lesson is uncalled for. Even the suggestion about using the command script was welcomed by myself. But the life comment I didn't take it well. I know I will have to do my bit of research also, I posted here. Because I thought someone else my have experienced it, and it would be quicker. That's it. I'm not here for smart rhetorical comments like so many tech forums are littered with. I have been impressed by the comments and help given in forum. And I would like it stay that way. That uncalled for comment of mine, was kinda of me saying "Please Leave, Take that garbage elsewhere"

willvincent's avatar

And that was me saying you can't expect it to "just work" you're going to have to do some initial config to get debugging worked, et al.. regardless of framework, environment, etc. it's part of the job. That was not a "life lesson" lighten up.

ojthejuice's avatar

@willvincent, I see you don't get. So i'm going to say thanks for setting my expectations. I HAD NO idea there wasn't a easy button involved in the process. Now I would like to get back on topic. So I did create artisan command script and setup the remote cli configuration so that I can debug it. That works well. But it still don't answer the initial post. So, if anyone else would like to help. I'm welcome for suggestions. Even @willvincent, I would welcome any comment or suggestion you have also.

willvincent's avatar

Oh no, I totally get it, you're thin skinned. Good luck. Hope you get it working :)

ojthejuice's avatar

Still littering the forum with worthless comments, huh.

Please or to participate in this conversation.