skip to Main Content

I seek guidance on importing classes and managing aliases in Laravel 11, which has introduced a new directory structure. In previous Laravel versions, I would handle these tasks in the app.php configuration file. However, Laravel 11 seems to have a different approach to managing class imports and aliases.

I would appreciate any assistance understanding how to import the Alias Class in this new context.

2

Answers


  1. I’ve just run into the same problem as you.. searching online I can’t find any ‘new’ way to do it, but fyi the ‘old’ way still works – just add your own ‘aliases’ array to config/app.php

    eg:

    'aliases' => Facade::defaultAliases()->merge([
        'MyAlias' => AppSomePathMyFacade::class,
    ])->toArray(),
    

    and don’t forget to import at the top:

    use IlluminateSupportFacadesFacade;
    
    Login or Signup to reply.
  2. You can do it using the Alias Loader or the PHP function class_alias from a service provider. Something like:

    use IlluminateFoundationAliasLoader;
    
        public function boot(): void
        {
            ...
            $this->bootAliases();
            ...
        }
    
        private function bootAliases(): void
        {
            AliasLoader::getInstance()->alias('LandingEditor', AppPresentationLandingEditor::class);
    
            // or
            // class_alias(AppPresentationLandingEditor::class, 'LandingEditor');
    
        }
    

    The alias loader is used by RegisterFacades (here is where the app.aliases config is being read) which get bootstraped by the Kernel. Behind de scenes ->load will use class_alias but in a lazy manner so if you’ll use that alias everywhere it may be more practical just to use class_alias. Until the official way to register aliases appear, I think it can be done this way.

    https://github.com/laravel/framework/blob/v11.0.0/src/Illuminate/Foundation/Http/Kernel.php#L46

    https://github.com/laravel/framework/blob/v11.0.0/src/Illuminate/Foundation/Bootstrap/RegisterFacades.php#L27

    https://github.com/laravel/framework/blob/v11.0.0/src/Illuminate/Foundation/AliasLoader.php#L151

    https://github.com/laravel/framework/blob/v11.0.0/src/Illuminate/Foundation/AliasLoader.php#L167

    https://github.com/laravel/framework/blob/v11.0.0/src/Illuminate/Foundation/AliasLoader.php#L71

    https://www.php.net/manual/en/function.class-alias.php

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search