Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel Alias not finding class

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

like image 558
user2834482 Avatar asked Oct 23 '14 12:10

user2834482


2 Answers

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.

like image 152
ruuter Avatar answered Oct 17 '22 11:10

ruuter


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

like image 22
Marcin Nabiałek Avatar answered Oct 17 '22 12:10

Marcin Nabiałek