FerranMunoz's avatar

Laravel ReflectionException: Class app\Services\UserService does not exist

Hello!

I'm working in a Laravel project and I created all the structure like repository, services, etc. But, when in the controller I call the service in the constructor with dependency injection and then starts the application, the web crash.

ReflectionException in Container.php line 809: Class app\Services\UserService does not exist

In ASP .NET MVC, for dependency injection we have tools like Autofac, when you tells to application that have to initializate the class/service before you injects it. But in Laravel I didn't found something like this.

I look the code and I think that all is correct, so, I don't know where is the problem.

Controller:

<?php

namespace App\Http\Controllers;

use app\Services\UserService;

class UserController extends ProjectController
{
    protected $user;
    
    public function __construct(UserService $user)
    {
        $this->user = $user;
    }
    
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        return view('users.index');
    }
}

Servicio

<?php
namespace app\Services;

use app\Repositories\UserRepository;

class UserService
{
    protected $user;
    
    public function __construct(UserRepository $user)
    {
        $this->user = $user;
    }
    
    public function all()
    {
        return $this->servicio->all();
    }
}

Repositorio

<?php
namespace app\Repositories;

use App\User;

class UserRepository
{
    protected $user;
    
    public function __construct(User $user)
    {
        $this->user = $user;
    }
    
    public function all()
    {
        return $this->user->all();
    }
}

Also, I tried something like composer dump-autoload and composer update but doesn't work.

Thanks

0 likes
3 replies
Sti3bas's avatar
Sti3bas
Best Answer
Level 53

@ferranmunoz App should start with a capital A.

use App\Services\UserService; instead of use app\Services\UserService;.

namespace App\Services; instead of namespace app\Services;.

use App\Repositories\UserRepository; instead of use app\Repositories\UserRepository;.

namespace App\Repositories; instead of namespace app\Repositories;.

https://github.com/laravel/laravel/blob/c78a1d8184f00f8270d8a135cc21590837b6bfbd/composer.json#L35

2 likes
Misha_lucky_boy's avatar

@Sti3bas thanks! My IDE automatically changed namespace registr when creating a class. Therefore, if a similar error occurs, I also recommend checking the namespace. Thank you bro

FerranMunoz's avatar

Yeah, you're right. I didn't realise of this detail... This is because Eclipse did like this when I create the class.

Well, now it works :)

Thank you!!

1 like

Please or to participate in this conversation.