Atef95
1 week ago
211
3
Laravel

Using facades in config files ?

Posted 1 week ago by Atef95

Hey artisans

I would like to know is there a way to use facades in config files ?

I'm getting Class 'LanguageConfiguration' not found error !

I have a config file from a package called translatable.php

'locales' => [
'en' ,
'fr' 
]


I wanted to dynamically add languages from my application in order to avoid manually setting the languages in this file

so I created a facade and I transformed it as below

    'locales' => LanguageConfiguration::getLanguageConfigs('locales'),


That's my facade code


<?php

namespace App\Facades;

use Illuminate\Support\Facades\Facade;

class LanguageFacade extends Facade
{

    protected static function getFacadeAccessor()
    {return 'languages';}

}



Helper.php


<?php
namespace App\Helpers;

use App\Modules\Language\Models\Language;
use Illuminate\Support\Facades\Cache;

class Helper
{

    public function getLanguageConfigs($type)
    {
        switch ($type) {
            case 'locales':

                return Language::pluck('prefix')->toArray();

                break;
            case 'locales_names':

                return Language::pluck('name', 'prefix')->toArray();

                break;

            case 'flush':

                Cache::flush();
                \Artisan::call('config:cache');
                \Artisan::call('cache:clear');

                break;
        }
    }
}




Language Service Provider


<?php

namespace App\Providers;

use App\Helpers\Helper;
use Illuminate\Support\Facades\App;
use Illuminate\Support\ServiceProvider;

class LanguageServiceProvider extends ServiceProvider
{
    /**
     * Register services.
     *
     * @return void
     */
    public function register()
    {
        App::bind('languages', function () {

            return new Helper;

        });
    }

    /**
     * Bootstrap services.
     *
     * @return void
     */
    public function boot()
    {
        //
    }
}




app.php

  'LanguageConfiguration' => App\Facades\LanguageFacade::class,

is there a way to fix this ?

Please sign in or create an account to participate in this conversation.