0
votes

Building simple Laravel backend app. Trying to keep controller clean and put all the business logic into Service which will use Model to query data.

I have tried few different options (examples) found here and documentation. Also run composer dump-autoload and composer update. still getting error that Service class does not exist.

CarController.php

<?php

namespace App\Http\Controllers;

use App\Services\CarService;

class CarController extends Controller
{

    protected $carService;

    public function __construct(CarService $carService)
    {
        $this->carService = $carService;
    }

    public function getCar()
    {
        return $carService::getCar();
    }
}
?>

CarService.php

<?

namespace App\Services;

class CarService
{
    public function getCar()
    {
        return 'Hello';
    }

}
?>

When calling the getCar function in controller, getting error:

<?

namespace App\Services;

class CarService
{
    public function getCar()
    {
        return 'Hello';
    }

}
?>

I got the following error in the Postman

{ "message": "Class App\Services\CarService does not exist", "exception": "ReflectionException", "file": "/home/MyDev/BackEnd/vendor/laravel/framework/src/Illuminate/Container/Container.php", "line": 826, "trace": [ { "file": "/home/MyDev/BackEnd/vendor/laravel/framework/src/Illuminate/Container/Container.php", "line": 826, "function": "getClass", "class": "ReflectionParameter", "type": "->"

(I'm using Postman to call API which call the controller. not sure why raw response is printing out the content of CarService and same time saying that it's not exist...)

thanks

2
Update: I'm using Visual Studio Code and it seems that when I add model name into __construct, it shows me help hover text that this is a class of Car extends Model. when I change it back to my service class, it doesn't solve the name... not sure if that's VS Code issue or I'm missing some configurationminaise

2 Answers

2
votes

Oh man, found the issue. My service php tag was just <?, but it HAVE TO be <?php

Added php and class was found, all works. oh man...

1
votes

You are doing everything right except for the call to the $carService you should refer to the class instance in order to access it, so try this in your controller instead:

public function getCar()
{
    return $this->carService->getCar();
}

If you want to access it as a static method CarService::getCar() then you won't need to inject the service in the controller, and you will need to change the signature of the function to be public static function getCar() in your service class.