Search code examples
phplaravelstartup

Execute a function when starting a Laravel application


I want to execute a function when I start my Laravel application.
Until now I used the boot function of the "AppServiceProvider" but then my function is executed very often.
How can I execute my function once at startup?

This is my code so far:

class AppServiceProvider extends ServiceProvider
{
    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
        //
    }

    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        //
        SocialController::init();
    }
}

Solution

  • There is an awesome feature in laravel Service Container called Singleton

    this feature everey thing you bind to it works for one time only that is mean that your an instance of class for example will be the same

    it's helpful for something like registering apiToken for third party token as you try i think

    so all you need os to write something like this

    $this->app->bind(SocialController::class, function ($app) {
        return SocialController::init();
    });