Reputation: 1025
I try to make a new custom class in laravel 5.4 to check the user type.
I add this new class in a new folder app\ItSolution, code:
<?php
namespace App\ItSolution;
class DemoClass {
public function getPermission() {
switch(Auth::user()->user_type_id) {
case 1:
return 'admin';
break;
case 2:
return 'promoter';
break;
case 3:
return 'customer';
break;
default:
return false;
}
}
}
I want to use this class in all my app , so i try to make a new ServiceProvider, code :
<?php
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
use App;
class AuthLibServiceProvider extends ServiceProvider
{
/**
* Bootstrap the application services.
*
* @return void
*/
public function boot()
{
//
}
/**
* Register the application services.
*
* @return void
*/
public function register()
{
App::bind('democlass', function()
{
return new \App\ItSolution\DemoClass;
});
}
}
And i make a new facade for my class in the same folder app\ItSolution, code:
<?php
namespace App\ItSolution;
use Illuminate\Support\Facades\Facade;
class DemoClassFacade extends Facade {
protected static function getFacadeAccessor() { return 'democlass'; }
}
After that i add this line in app/config.php
'aliases' => [
...
'DemoClass'=> App\ItSolution\DemoClassFacade::class,
]
'providers' => [
...
App\Providers\AuthLibServiceProvider::class,
]
But i have this error when i try to use the DemoClass alias in my controller DemoClass::getPermission():
Class 'App\Http\Controllers\DemoClass' not found
How can i fix that please, Thnaks.
Upvotes: 1
Views: 2919
Reputation: 9161
In laravel 5.4 you don't need a Service Provider to register a facade, you can use automatic Facadaes, you have to define only the DemoClass.
i.e in a controller:
use Facades\ {
App\ItSolution\DemoClass
};
And call the function
DemoClass::getPermission()
Source here
Upvotes: 1
Reputation: 163758
You're registering this class as facade, so you'll need to add this to the beginning of the class:
use DemoClass;
Or you can just use full namespace when using the facade:
\DemoClass::
Upvotes: 1