Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Laravel Aliases Laravel Package

craftcms/laravel-aliases

Provides Craft CMS–style alias support for Laravel. Define and resolve @aliases (e.g. @web, @root) in config and use them to build paths/URLs consistently across environments, keeping code cleaner and avoiding hard‑coded directory strings.

Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require craftcms/laravel-aliases
    

    No additional configuration is required—it auto-registers via Laravel’s service provider.

  2. First Use Case: Define an alias in config/aliases.php (created automatically):

    return [
        'app' => [
            'aliases' => [
                'app' => app_path(),
                'config' => config_path(),
                // Custom alias example:
                'myPackage' => base_path('vendor/my-package'),
            ],
        ],
    ];
    

    Use it in code:

    $path = alias('myPackage');
    
  3. Key Files:

    • config/aliases.php: Centralized alias definitions.
    • app/Providers/AppServiceProvider.php: Auto-loaded by the package (no manual binding needed).

Implementation Patterns

Core Workflows

  1. Dynamic Aliases: Override aliases dynamically in runtime (e.g., for testing or environment-specific paths):

    alias()->set('tempStorage', storage_path('framework/test'));
    
  2. Integration with Laravel Features:

    • Service Providers: Use aliases to reference config/files cleanly:
      $this->loadViewsFrom(alias('resources/views/vendor/my-package'));
      
    • Facades: Reference aliased paths in facades for consistency:
      class MyFacade extends Facade {
          protected static function getFacadeAccessor() {
              return alias('myPackage')->path('services');
          }
      }
      
  3. Package Development:

    • Bootstrap Paths: Alias vendor/package roots for modularity:
      alias()->set('myPackage', __DIR__.'/../../../');
      
    • Asset Publishing: Use aliases in publishes() to avoid hardcoding:
      $this->publishes([
          alias('myPackage').'/config/my-package.php' => config_path('my-package.php'),
      ]);
      
  4. Environment-Specific Paths: Leverage Laravel’s config caching to define environment-aware aliases:

    // config/aliases.php
    'aliases' => [
        'logs' => env('APP_ENV') === 'local'
            ? storage_path('logs/dev')
            : storage_path('logs/prod'),
    ],
    

Gotchas and Tips

Pitfalls

  1. Caching Conflicts:

    • Laravel caches config (including aliases.php). Clear the cache after changes:
      php artisan config:clear
      
    • Debugging: Use alias()->get('key') to verify values at runtime.
  2. Circular Dependencies: Avoid defining aliases that reference other aliases in the same config file (e.g., alias('a') pointing to alias('b')). Use absolute paths or resolve dependencies manually.

  3. Namespace Collisions:

    • Aliases are case-insensitive. Use descriptive names (e.g., myPackageConfig vs. config).
  4. Testing Quirks:

    • Mock aliases in tests:
      alias()->set('testAlias', __DIR__.'/stubs');
      
    • Reset aliases after tests to avoid pollution:
      alias()->clear();
      

Tips

  1. Validation: Add validation to aliases.php to catch typos early:

    if (!file_exists(alias('criticalPath'))) {
        throw new RuntimeException("Alias 'criticalPath' points to non-existent directory.");
    }
    
  2. IDE Support:

    • Use PHPStorm’s "Go to Symbol" (Ctrl+Shift+Alt+N) to navigate aliased paths.
    • Add @property string $aliasName to classes for IDE autocompletion.
  3. Performance:

    • Prefer alias('key') over alias()->get('key') for micro-optimizations (method call vs. property access).
    • For heavy usage, cache resolved paths:
      static $cachedPaths = [];
      $path = $cachedPaths['myAlias'] ?? alias('myAlias');
      
  4. Extending the Package:

    • Custom Resolvers: Override the AliasManager to add logic (e.g., URL-to-path resolution):
      $this->app->singleton('alias', function () {
          return new class extends \Craftcms\Aliases\AliasManager {
              public function resolve($name) {
                  if (str_starts_with($name, 'http://')) {
                      return $this->convertUrlToPath($name);
                  }
                  return parent::resolve($name);
              }
          };
      });
      
    • Event Listeners: Listen for aliases.defined events to react to alias changes.
  5. Debugging:

    • Dump all aliases:
      dd(alias()->all());
      
    • Check for undefined aliases:
      if (!alias()->has('missingAlias')) {
          throw new \InvalidArgumentException("Alias 'missingAlias' is not defined.");
      }
      
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
davejamesmiller/laravel-breadcrumbs
artisanry/parsedown
christhompsontldr/phpsdk
enqueue/dsn
bunny/bunny
enqueue/test
enqueue/null
enqueue/amqp-tools
bower-asset/punycode
bower-asset/inputmask
bower-asset/jquery
bower-asset/yii2-pjax
laravel/nova
spatie/laravel-mailcoach
spatie/laravel-superseeder
laravel/liferaft
nst/json-test-suite
danielmiessler/sec-lists
jackalope/jackalope-transport
twbs/bootstrap4