12

I am trying to register an Alias to a class, but Laravel can't find the class, i can reference the class directly in my controller, so i know its loaded correctly.

here is my code:

    'aliases' => array(
        'FrontendAssets' => 'Lib\FrontendAssets',
    )

the class I am trying to make an alias for

class FrontendAssets{

    protected static $styles = [];
    protected static $scripts = [];

    public static function styles(){
        return static::assets(static::$styles);
    }

    public static function addStyle($style){
        static::$styles[] = $style;
    }

    public static function scripts(){
        $scripts = static::assets(static::$scripts);
        return $scripts;
    }

    public static function addScript($script){
        static::$scripts[] = $script;
    }

    public static function assets($assets){
        return array_map(function ($asset){
                return $asset;
        }, array_unique($assets));
    }
} 

This is what i am trying to call in my controller

FrontendAssets::assets();

I have tried adding namespaces but still no joy.

If i use \FrontendAssets::assets(); in my controller, I can use the class so I know it is defiantly been loaded

Kiran Maniya
  • 8,453
  • 9
  • 58
  • 81
user2834482
  • 437
  • 2
  • 6
  • 14

4 Answers4

16
php artisan config:clear

Might help also. In case you have previously cached config files with config:cache since aliases are defined in app config.

ruuter
  • 2,453
  • 2
  • 30
  • 44
15

First run composer dump-autoload to make sure the class can be found.

Now, when you have controller in namespace, for example:

<?php

namespace App\Http\Controllers;

class YourController {

}

if you want to access FrontendAssets class you need to add leading backslash, so FrontendAssets::assets(); won't work but \FrontendAssets::assets(); will work.

You can alternatively import this class:

<?php

namespace App\Http\Controllers;

use FrontendAssets;

class YourController {

}

and now you will be able to use FrontendAssets::assets();. If it's unclear you might want to look also for explanation at How to use objects from other namespaces and how to import namespaces in PHP

Community
  • 1
  • 1
Marcin Nabiałek
  • 109,655
  • 42
  • 258
  • 291
0

Laravel caches the configuration to avoid runtime loading overhead. You have to run one of the given artisan commands.

Below given command will clear out the configurations cached previously.

php artisan config:clear

And the below given command will clear and re-cache the configuration.

php artisan config:cache

After clearing the configuration cache, you will be able to use that alias defined in config/app.php.

gre_gor
  • 6,669
  • 9
  • 47
  • 52
Kiran Maniya
  • 8,453
  • 9
  • 58
  • 81
0

You need to empty cache and dump the autoloads, you can do it with a single command:

composer dump && php artisan optimize
Mattia S.
  • 423
  • 7
  • 9