🧠 Service Layer + Repository Pattern
> This is one of my backend architecture approaches, especially when I build medium to large Laravel applications, to keep the system clean, scalable, and maintainable.
Route
↓
Controller
↓ injects
Service
↓ uses Trait
Service
↓ injects
Repository
↓
Model
↓
Database🎯 Simple Idea
👉 I separate responsibilities clearly so each layer has one focused job
🧩 How the Flow Works
🧩 Full Flow
User Request
↓
Route
↓
Controller
↓ Dependency Injection
UserService
↓ uses Trait (shared logic)
UserRepository
↓
User Model
↓
Database🧱 Example Flow
Controller injects Service
class UserController extends Controller
{
public function __construct(
protected UserService $userService
) {}
public function store(StoreUserRequest $request)
{
return $this->userService->createUser($request->validated());
}
}Service injects Repository and uses Trait
class UserService
{
use UploadFileTrait;
public function __construct(
protected UserRepository $userRepository
) {}
public function createUser(array $data)
{
if (isset($data['avatar'])) {
$data['avatar'] = $this->uploadFile($data['avatar']);
}
return $this->userRepository->create($data);
}
}Trait used inside Service
trait UploadFileTrait
{
public function uploadFile($file)
{
return $file->store('uploads');
}
}Repository handles database logic
class UserRepository
{
public function create(array $data)
{
return User::create($data);
}
}📌 Dependency Injection Flow
Controller needs UserService
→ Laravel Service Container resolves UserService
UserService needs UserRepository
→ Laravel Service Container resolves UserRepository
UserRepository uses User Model
→ Model interacts with Database👉 I rely on Laravel’s Service Container to automatically resolve dependencies, keeping the code clean and loosely coupled.
🧠 Why I Use This Approach
⚖️ Trade-offs
📌 Practical Rule
Controller → request/response only (thin)
Service → business logic (core layer)
Trait → reusable service logic
Repository → database queries only
Model → data structure & relationships
View → presentation layer💬 Summary
This is one of my backend architecture approaches, especially for medium to large Laravel applications, where I apply a Service Layer with Repository Pattern, combined with Dependency Injection and Traits.
Request
→ Controller
→ Service
→ Trait (if needed)
→ Repository
→ Model
→ Database👉 This allows me to build systems that are clean, maintainable, testable, and scalable for production