Reputation: 153
I would like to include a class for every controller to use. Here is what I tried with no luck.
In the Controller.php file, I added this line of code:
use App\Lib\RequestType;
Then in my controller UserController.php, I called a test function.
dd(RequestType::test());
But a fatal error is thrown.
Class 'App\Http\Controllers\RequestType' not found
What is laravel looking for the class in the Controllers folder. Shouldn't UserController inherit the Controller class?
Thanks in advance
Upvotes: 0
Views: 5650
Reputation: 2371
There is no way to auto-magically have a class everywhere.
PHP use
is not inherited by extending classes. Even Laravel's Facades have to specified.
You can store the class in the App\Http\Controllers\Controller->__contruct()
to make it more easily manageable.
// App\Http\Controllers\Controller
public function __construct()
{
$this->requestType = new RequestType();
}
// App\Http\Controllers\FooController
public function __construct()
{
parent::__contruct();
}
public function index()
{
$requestType = $this->requestType;
}
Upvotes: 0
Reputation: 2458
If you are trying to write a static class and call it by use
, then one option is to make use of autoload feature of composer, which will enable the class to be used anywhere.
"autoload": {
"psr-4": {
"App\\": "app/"
},
"classmap": [
"app/Lib"
]
},
Then in any controller
use RequestType;
then
dd(RequestType::test());
Note: Function test should be like
public static function test()
Upvotes: 0