PHPackages                             avoqado-dev/laravel-usecase - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Utility &amp; Helpers](/categories/utility)
4. /
5. avoqado-dev/laravel-usecase

ActiveLibrary[Utility &amp; Helpers](/categories/utility)

avoqado-dev/laravel-usecase
===========================

A lightweight, type-safe Use Case pattern implementation for Laravel with business rule validation

v2.0.0(1mo ago)22513↑70.8%1[1 PRs](https://github.com/avoqado-dev/laravel-usecase/pulls)MITPHPPHP ^8.2CI passing

Since Dec 14Pushed 1mo agoCompare

[ Source](https://github.com/avoqado-dev/laravel-usecase)[ Packagist](https://packagist.org/packages/avoqado-dev/laravel-usecase)[ RSS](/packages/avoqado-dev-laravel-usecase/feed)WikiDiscussions main Synced 3d ago

READMEChangelog (3)Dependencies (18)Versions (5)Used By (0)

🎯 Laravel UseCase
=================

[](#-laravel-usecase)

 **A lightweight, type-safe Use Case pattern implementation for Laravel with built-in business rule validation**

 [![Tests](https://github.com/avoqado-dev/laravel-usecase/workflows/Code%20Quality/badge.svg)](https://github.com/avoqado-dev/laravel-usecase/actions) [![Latest Version](https://camo.githubusercontent.com/c55f45a3d24c5ecc7a3991fdf54bf4c242894f1eebf70d250fa67d8ef94eceb0/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f61766f7161646f2d6465762f6c61726176656c2d757365636173652e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/avoqado-dev/laravel-usecase) [![Total Downloads](https://camo.githubusercontent.com/e3759fcff1a095e0827e5f91bf2e580c63ea22382f81c9db9325f7a287358faf/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f61766f7161646f2d6465762f6c61726176656c2d757365636173652e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/avoqado-dev/laravel-usecase) [![License](https://camo.githubusercontent.com/f5e6130db7e2aa68c988d9e7e4ac32e1dd9c6b5f8c3a08421fa356e6cfdad4a9/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f6c2f61766f7161646f2d6465762f6c61726176656c2d757365636173652e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/avoqado-dev/laravel-usecase) [![GitHub Stars](https://camo.githubusercontent.com/87f727a3b807fb9ca5ec9e61f6d474852905c8d6b00efeb9770ac15b9f19a981/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f73746172732f61766f7161646f2d6465762f6c61726176656c2d757365636173653f7374796c653d736f6369616c)](https://github.com/avoqado-dev/laravel-usecase)

---

📖 Table of Contents
-------------------

[](#-table-of-contents)

- [What is Laravel UseCase?](#-what-is-laravel-usecase)
- [Why Use This Package?](#-why-use-this-package)
- [Key Features](#-key-features)
- [Installation](#-installation)
- [Quick Start](#-quick-start)
- [Middleware Explained](#-middleware-explained)
- [Business Rules](#-business-rules)
- [Testing](#-testing)
- [Configuration](#-configuration)
- [Support &amp; Contribution](#-support--contribution)

---

🎯 What is Laravel UseCase?
--------------------------

[](#-what-is-laravel-usecase)

**Laravel UseCase** brings clean architecture principles to your Laravel applications by implementing the **Use Case pattern** (also known as Application Services or Command/Query pattern). It helps you organize your business logic into focused, testable, and reusable units that are completely independent of your HTTP layer.

Instead of fat controllers or bloated models, your business logic lives in dedicated Use Case classes that can be called from anywhere - controllers, jobs, commands, or even other use cases.

### The Problem It Solves

[](#the-problem-it-solves)

```
// ❌ Before: Fat Controller with mixed concerns
class UserController
{
    public function store(Request $request)
    {
        // HTTP validation
        $validated = $request->validate([...]);

        // Business rule checking
        if (User::where('email', $validated['email'])->exists()) {
            return back()->withErrors(['email' => 'Email taken']);
        }

        // Database transaction
        DB::beginTransaction();
        try {
            $user = User::create($validated);
            event(new UserCreated($user));
            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();
            throw $e;
        }

        // Logging
        Log::info('User created', ['user_id' => $user->id]);

        return redirect()->route('users.show', $user);
    }
}
```

```
// ✅ After: Clean Controller with Use Case
class UserController
{
    public function store(CreateUserRequest $request)
    {
        $userId = Mediator::dispatch(new CreateUser(
            name: $request->validated('name'),
            email: $request->validated('email'),
            password: $request->validated('password'),
        ));

        return redirect()->route('users.show', $userId);
    }
}
```

---

🚀 Why Use This Package?
-----------------------

[](#-why-use-this-package)

### ✨ Benefits

[](#-benefits)

BenefitDescription**🎯 Separation of Concerns**Business logic is completely isolated from HTTP, making it reusable across controllers, jobs, commands, and tests**🔒 Type Safety**Full PHP 8.2+ type hints and generics catch errors at compile time, not runtime**🧪 Testability**Test business logic in isolation without booting the HTTP layer or database**📦 Maintainability**Clear, predictable structure makes onboarding new developers faster**♻️ Reusability**Use cases can be called from anywhere - no duplication needed**🎨 Business-First**Domain rules are first-class citizens with dedicated validation layer**🔧 Laravel-Native**Uses familiar Laravel patterns - facades, container, middleware, events**📊 Observability**Built-in logging, caching, and transaction management**⚡ Performance**Automatic caching and atomic locks prevent redundant work**🛡️ Safety**Database transactions and retry logic built-in---

✨ Key Features
--------------

[](#-key-features)

- ✅ **Type-Safe** - Uses PHP 8.2+ generics for return type safety
- ✅ **Business Rule Validation** - Separates domain rules from HTTP validation
- ✅ **Middleware Pipeline** - Familiar Laravel-style middleware for cross-cutting concerns
- ✅ **Zero Dependencies** - Only requires Laravel, no third-party packages
- ✅ **Comprehensive Testing Utilities** - Full mocking and assertion capabilities
- ✅ **Artisan Generator** - Scaffold use cases with a single command
- ✅ **Built-in Middleware** - Transactions, caching, locks, logging out of the box
- ✅ **Laravel-Native Integration** - Uses facades, container, events naturally

---

📦 Installation
--------------

[](#-installation)

Install via Composer:

```
composer require avoqado-dev/laravel-usecase
```

The package will auto-register via Laravel's package discovery.

### Publish Configuration (Optional)

[](#publish-configuration-optional)

```
php artisan vendor:publish --tag=usecase-config
```

---

🚀 Quick Start
-------------

[](#-quick-start)

### 1. Generate a Use Case

[](#1-generate-a-use-case)

The easiest way to create a new use case is using the artisan command:

```
# Basic usage
php artisan make:usecase CreateUser --module=Users --entity=User

# With database transaction support
php artisan make:usecase CreateOrder --module=Orders --entity=Order --transaction

# With caching support
php artisan make:usecase GetUserStats --module=Users --entity=User --cache

# With atomic lock support
php artisan make:usecase ProcessPayment --module=Payments --entity=Payment --lock

# Combine multiple features
php artisan make:usecase ComplexOperation --module=Operations --entity=Operation --transaction --cache --lock
```

This generates both the **Request** and **Handler** classes in `app/UseCases/{Module}/{Entity}/{UseCaseName}/`.

### 2. Define Your Request

[](#2-define-your-request)

```
