I'm trying to make a simple class in a fresh-installed Laravel. For this I have created a folder app/Convert and put the php-file there. The class looks like this:
<?php
namespace App\Convert;
class Converter
{
public function __construct()
{
...Code
}
}
Now when I try to access it from Tinker:
use App\Convert\Converter;
new Converter;
I get:
PHP Fatal error: Class 'App/Convert/Converter' not found in Psy Shell code on line 1
What am I doing wrong? As I understand laravel should autoexecute the files inside the app folder and it's subfolders or am I mistaken?
EDIT: Sorry the first time I wrote it wrong (I just played around so much with the namespaces so I took the wrong version). The problem was actually that the file name was something else than Converter.php, so when I changed it to Converter.php things started to change. I would set the Devon's answer as the correct answer if he put it as an answer not comment. So write it here:
Name of the file containing class should be the same as the class name. And the path to the file is the same as the namespace path. (see the Matthew's comment below his answer)
sometimes it is necessary to clear the cache, this command worked in my case:
composer dump-autoload
I hope it works for you too
regards
Your namespace in the class differs from how you are trying to import it. You set it as App\Convert
there. You would need to import it as App\Convert\Converter
.
The fully qualified class name for a class includes the namespace AND the class name. So, for instance, if you have a class called Bar
with a namespace of App\Foo
, the fully qualified class name is App\Foo\Bar
, and to be able to use it as Bar
, you'd need to import it as follows:
use App\Foo\Bar;
Also, as Devon said below, you'd need to have the file containing the class at app/Foo/Bar.php
for the default Laravel autoloader configuration to pick it up.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With