Search code examples
phplaravelerror-handlingservice

Class 'App\TestService' 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 'App\TestService' not found {"userId":1,"exception":"[object] (Error(code: 0): Class 'App\TestService' not found at /Backend/app/Http/Controllers/TestController.php:8)

Code

TestController.php:

<?php
namespace App\Http\Controllers;
use App\TestService;

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

TestService.php:

<?php
namespace App;
use App\TestService;

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 App\TestService; 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.


Solution

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

    TestService.php:

    <?php
    namespace App\Services\Tests;
    
    class TestService
    {
        public static function getTest()
        {
            return "test";
        }
    }
    

    TestController.php:

    <?php
    namespace App\Http\Controllers;
    use App\Services\Tests\TestService;
    
    class TestController extends Controller
    {
        public function test()
        {
            //Call service class like.
            return response()->json(TestService::getTest());
        }
    }