Class ‘AppTestService’ not found – Laravel

Problem

I created service TestService, that I use in colntroller file TestController in function test().

When I called test(), I got an error:

local.ERROR: Class ‘AppTestService’ not found {“userId”:1,”exception”:”[object] (Error(code: 0): Class ‘AppTestService’ not found at /Backend/app/Http/Controllers/TestController.php:8)

Code

TestController.php:

<?php
namespace AppHttpControllers;
use AppTestService;

class TestController extends Controller
{
    public function test()
    {
        return response()->json(TestService::getTest());
    }
}

TestService.php:
<?php
namespace App;
use AppTestService;

class TestService
{
    public static function getTest()
    {
        return "test";
    }
}

What I tried

  • I checked all the names and they are correct.
  • When I wrote in the colntroller file use AppTestService;
    I had autocomplete, so the service and name are visible.
  • I used these commands to refresh the files: php artisan serve and php artisan clear-compiled.

But it still doesn’t work.

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

You have not correctly defined Namespace.
The namespace must be a directory path where you have created a file.

TestService.php:

<?php
namespace AppServicesTests;

class TestService
{
    public static function getTest()
    {
        return "test";
    }
}

TestController.php:
<?php
namespace AppHttpControllers;
use AppServicesTestsTestService;

class TestController extends Controller
{
    public function test()
    {
        //Call service class like.
        return response()->json(TestService::getTest());
    }
}


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x