Matthew Hodge
Full Stack Developer

There's no one size fits all solution when it comes to structuring your Laravel applications. The right pattern depends on many factors such as team size, project complexity, long-term maintenance, and even your team's familiarity with certain approaches. What works for a solo developer on a small project might not scale for a large team building a business-critical application.

As Laravel developers, most of us start by putting business logic directly in controllers. It's quick, simple, and gets the job done, until your app grows and “fat controllers” start to slow you down. At that point, it's time to reach for better patterns.

In this post, I'll walk through five common approaches to structuring business logic in Laravel: Controllers, Service Classes, Action Classes, Domain-Driven Design (DDD), and the Repository Pattern. I'll share when to use each, their pros and cons, and practical examples.


1. Controllers (CRUD)

The classic approach: keep everything in the controller.

When to Use:

  • Small projects
  • Prototypes
  • Quick-and-dirty features

Pros:

  • Fast to write
  • Easy to follow for beginners

Cons:

  • Controllers get bloated (“fat controllers”)
  • Hard to test
  • Logic is not reusable

Example:

// app/Http/Controllers/PostController.php

public function store(Request $request)
{
    $validated = $request->validate([
        'title' => 'required|string',
        'body' => 'required|string',
    ]);
    $post = Post::create($validated);
    // Maybe some more business logic here...
    return redirect()->route('posts.index');
}

2. Service Classes

As your app grows, business logic in controllers becomes hard to manage. Service classes move this logic into dedicated classes, keeping controllers slim.

When to Use:

  • Medium to large projects
  • When logic is reused in multiple places
  • For improved testability

Pros:

  • Keeps controllers clean
  • Logic is reusable
  • Easier to test

Cons:

  • More files/structure
  • Can become “anemic” (just wrappers) if not careful

Example:

// app/Http/Controllers/PostController.php
public function construct(PostService $service){
    $this->service = $service;
}

public function store(Request $request)
{
    $post = $this->service->create($request->validated());
    return redirect()->route('posts.index');
}

// app/Services/PostService.php
namespace App\Services;

class PostService
{
    public function create(array $data)
    {
        // Business logic for creating a post
        return Post::create($data);
    }
}

3. Action Classes (Action Pattern)

Action classes encapsulate a single, focused task—like “CreatePost” or “SendInvoice.” They're great for isolating business logic, making it reusable and testable.

When to Use:

  • When you want to encapsulate and reuse specific business operations
  • For clear, single-responsibility units of work

Pros:

  • Highly focused and reusable
  • Easy to test
  • Encourages single responsibility

Cons:

  • Can result in many small files
  • May overlap with service classes if not careful

Example:

// app/Http/Controllers/PostController.php
public function store(Request $request, CreatePost $action)
{
    $post = $action->execute($request->validated());
    return redirect()->route('posts.index');
}

// app/Actions/CreatePost.php
namespace App\Actions;

use App\Models\Post;

class CreatePost
{
    public function execute(array $data)
    {
        // Business logic for creating a post
        return Post::create($data);
    }
}

Service Classes vs Action Classes: What's the Difference?

At first glance, Service Classes and Action Classes in Laravel look very similar: both move business logic out of controllers and into dedicated classes, both make your code more testable and reusable, and both help keep your controllers slim.

But there are some key differences in philosophy and usage:

Service Classes

  • Purpose: Group related business logic that spans multiple actions or concerns. For example, a PostService might handle creating, updating, and deleting posts, as well as more complex post-related operations.
  • Structure: Typically contains multiple public methods, each representing a different operation.
  • Example Use: When you have a set of related operations that share dependencies or need to coordinate logic.
class PostService
{
    public function create(array $data) { /* ... */ }
    public function update(Post $post, array $data) { /* ... */ }
    public function delete(Post $post) { /* ... */ }
}

Pros:

  • Centralizes related logic
  • Good for operations that are conceptually grouped
  • Can manage dependencies via constructor injection

Cons:

  • Can become bloated with too much logic
  • Less explicit about single responsibilities

Action Classes

  • Purpose: Encapsulate a single, focused operation or “action” (e.g., CreatePost, SendWelcomeEmail). Each class does one thing and does it well.
  • Structure: Usually one public method (often execute or handle), representing the action.
  • Example Use: When you want to isolate a specific task, especially if it will be reused in multiple places (controllers, jobs, events, etc.).
class CreatePost
{
    public function execute(array $data) { /* ... */ }
}

Pros:

  • Highly focused and easy to test
  • Encourages single responsibility principle
  • Easy to compose and reuse in different parts of your app (controllers, jobs, commands, etc.)

Cons:

  • Can result in many small files
  • If not organized, may lead to scattered logic

When to Use Each?

  • Use a Service Class when you have a set of related operations that share dependencies or need to coordinate logic. For example, a UserService that manages user registration, profile updates, and password resets.
  • Use an Action Class when you want to isolate a single operation, especially if it will be reused in multiple places. For example, a CreateInvoice action that you call from a controller, a scheduled job, or an event listener.

Tip:
You can also combine both! A Service Class might orchestrate several Actions, or Actions might use a Service internally for shared logic.

Practical Example

Suppose your app lets users create posts, and you want to send a notification after a post is created.

With Service Class:

  • PostService@create handles both saving the post and sending the notification.

With Action Class:

  • CreatePost@execute handles saving the post.
  • SendPostNotification@execute handles the notification.
  • The controller (or a service) coordinates the two actions.

4. Domain-Driven Design (DDD)

DDD is an advanced approach that organizes code by domain concepts rather than technical type. It's ideal for large, complex, or long-lived projects.

When to Use:

  • Large, complex, or business-critical projects
  • When working with multiple teams
  • When you need clear domain boundaries

Pros:

  • Highly maintainable and scalable
  • Clear boundaries and business language
  • Aligns code with real-world concepts

Cons:

  • Steep learning curve
  • More boilerplate
  • Overkill for small apps

Example Structure:

app/
  Domain/
    Blog/
      Actions/
      ValueObjects/
      Aggregates/
      Repositories/
    User/
  Application/
  Infrastructure/
  Presentation/

You might have a CreatePost action inside Domain/Blog/Actions, and aggregates or value objects representing your business rules.


5. The Repository Pattern

The Repository pattern provides a layer between your business logic and data access. Instead of interacting directly with Eloquent models, your controller, services or actions talk to repositories, making your code more flexible and testable.

When to Use:

  • When you want to decouple your business logic from Eloquent or your database.
  • In large or complex apps, or when following DDD.

Pros:

  • Makes swapping data sources easier (e.g., database, API, cache).
  • Improves testability (you can mock repositories).
  • Enforces a contract for data access.

Cons:

  • Adds extra boilerplate in simple apps.
  • Can be overkill for small projects.

Example:

// app/Repositories/PostRepository.php
interface PostRepository
{
    public function all();
    public function find($id);
    public function create(array $data);
}

// app/Repositories/EloquentPostRepository.php
class EloquentPostRepository implements PostRepository
{
    public function all() { return Post::all(); }
    public function find($id) { return Post::find($id); }
    public function create(array $data) { return Post::create($data); }
}

You can then inject and use PostRepository in your controller, services or actions instead of Eloquent directly.

Binding the Repository in a Service Provider: To make Laravel resolve PostRepository to your EloquentPostRepository, add the following to your AppServiceProvider or a dedicated service provider:

// app/Providers/AppServiceProvider.php

use App\Repositories\PostRepository;
use App\Repositories\EloquentPostRepository;

public function register()
{
    $this->app->bind(PostRepository::class, EloquentPostRepository::class);
}

Using the repository in your controller for example might look something like this:

// app/Http/Controllers/PostController.php
class PostController extends Controller
{
    protected $postRepository;

    public function __construct(protected PostRepository $postRepository)
    {
        $this->postRepository = $postRepository;
    }

    public function index()
    {
        $posts = $this->postRepository->all();
        return view('posts.index', compact('posts'));
    }
}

Comparison Table

PatternWhen to UseProsCons
ControllersSmall/simple appsQuick, simpleFat controllers
Service ClassMedium/large appsTestable, reusableMore structure
Action ClassReusable tasks, clarityFocused, testable, reusableMany small files
DDDLarge/complex appsScalable, maintainableLearning curve
RepositoryAbstraction, DDD, testingDecouples data access, testableBoilerplate, overkill for small apps

Conclusion

There's no one-size-fits-all answer. Start simple, controllers are fine for small apps. As your app grows, refactor business logic into service classes or action classes. For truly complex domains, consider DDD. The key is to recognize when it's time to evolve your architecture.


Using Scoped Relationships in Laravel Eloquent

When working with Laravel Eloquent, you’ll often need to filter or extend your relationships to suit your app’s needs. Scoped relationships let you add custom constraints to your relationships, making your models more expressive and your queries more reusable.

Let’s walk through some concrete examples to help you understand and use scoped relationships in your own projects!

What is a Scoped Relationship?

A scoped relationship is simply a relationship method on your model that applies extra query constraints. For example, you might want to easily fetch only the “featured” posts for a user, not just all posts.

Example: User and Posts

Let’s say you have a User model and a Post model. A user can have many posts:

// app/Models/User.php

public function posts(): HasMany
{
    return $this->hasMany(Post::class)->latest();
}

Now, let’s say you want a quick way to get just the featured posts for a user. You can add a new relationship method that scopes the query:

public function featuredPosts(): HasMany
{
    return $this->posts()->where('featured', true);
}

Now you can do:

$featuredPosts = $user->featuredPosts;

Creating Models via Scoped Relationships

But what if you want to create a new featured post using this relationship? By default, the featured attribute won’t be set automatically:

$post = $user->featuredPosts()->create(['title' => 'My Post']);
// $post->featured is NOT true

Introducing withAttributes

Laravel has a withAttributes function which lets you specify default attributes for models created via the relationship:

public function featuredPosts(): HasMany
{
    return $this->posts()->withAttributes(['featured' => true]);
}

Now, when you create a post via this relationship:

$post = $user->featuredPosts()->create(['title' => 'Featured Post']);
// $post->featured is TRUE!

Customizing Query vs. Creation

By default, withAttributes also adds a where clause to the query. If you only want the default attribute on creation, not as a query constraint, pass asConditions: false:

public function featuredPosts(): HasMany
{
    return $this->posts()->withAttributes(['featured' => true], asConditions: false);
}

When Should You Use Scoped Relationships?

  • When you want to DRY up your code and avoid repeating common query constraints.
  • When you want to make your model API more expressive (e.g., $user->publishedPosts, $user->archivedPosts).
  • When you want to provide sensible defaults for related model creation.

Real-World Use Case

Suppose you’re building a blog platform. You want to let users quickly fetch or create “draft” or “published” posts:

public function draftPosts(): HasMany
{
    return $this->posts()->withAttributes(['status' => 'draft']);
}

public function publishedPosts(): HasMany
{
    return $this->posts()->withAttributes(['status' => 'published']);
}

Now you can easily fetch or create posts in either state:

$draft = $user->draftPosts()->create(['title' => 'My Draft']);
$published = $user->publishedPosts()->create(['title' => 'My Article']);

Conclusion

Scoped relationships are a powerful way to make your Eloquent models more expressive and your code more maintainable. Try adding them to your own models to simplify your queries and model creation!


Laravel's tap helper is a powerful utility that allows you to work with a value and return it without breaking the chain of operations. Let's explore how it works and how to use it effectively.

The TAP Function

At its core, the tap helper is a simple yet powerful function:

if (! function_exists('tap')) {
    /**
     * Call the given Closure with the given value then return the value.
     *
     * @template TValue
     *
     * @param  TValue  $value
     * @param  (callable(TValue): mixed)|null  $callback
     * @return ($callback is null ? \Illuminate\Support\HigherOrderTapProxy : TValue)
     */
    function tap($value, $callback = null)
    {
        if (is_null($callback)) {
            return new HigherOrderTapProxy($value);
        }

        $callback($value);

        return $value;
    }
}

The function does two key things:

  1. If no callback is provided, it returns a HigherOrderTapProxy instance
  2. If a callback is provided, it executes the callback with the value and returns the original value

Basic Usage

The tap helper allows you to "tap" into a chain of methods to perform operations on an object while still returning the original value.

$user = tap(User::first(), function($user) {
    $user->update(['last_login' => now()]);
});

Why Use TAP?

Without tap, you might write:

$user = User::first();
$user->update(['last_login' => now()]);
return $user;

With tap, it's more concise:

return tap(User::first(), function($user) {
    $user->update(['last_login' => now()]);
});

Real-World Examples

Example 1: File Operations

use Illuminate\Support\Facades\Storage;

$path = tap(Storage::put('path/to/file.txt', 'contents'), function() {
    Cache::forget('file-cache');
    Log::info('File was updated');
});
$post = tap(Post::create([
    'title' => 'My Post',
    'content' => 'Post content'
]), function($post) {
    $post->tags()->attach([1, 2, 3]);
    $post->user->notify(new PostCreated($post));
});

Example 3: Collection Manipulation

$processedUsers = tap(User::all(), function($users) {
    $users->each->notify(new WelcomeNotification);
    Cache::put('users', $users);
});

Using TAP with Arrow Functions

PHP 7.4+ allows for more concise syntax:

$user = tap(User::first(), fn($user) => $user->update(['last_login' => now()]));

The tap() Method on Collections

Laravel collections include a tap method:

collect([1, 2, 3])
    ->tap(function($collection) {
        Log::info('Count: ' . $collection->count());
    })
    ->filter(fn($value) => $value > 1)
    ->tap(function($collection) {
        Log::info('Filtered Count: ' . $collection->count());
    });

// Count: 3  
// Filtered Count: 2  

Testing with TAP

TAP is particularly useful in tests:

public function test_user_creation()
{
    $user = tap(User::factory()->create(), function($user) {
        $this->assertDatabaseHas('users', [
            'id' => $user->id,
            'email' => $user->email
        ]);
    });

    $this->actingAs($user);
}

Common Use Cases

  1. Logging Operations:
$response = tap($service->process(), function($result) {
    Log::info('Process completed', ['result' => $result]);
});
  1. Cache Operations:
$posts = tap(Post::all(), function($posts) {
    Cache::put('all_posts', $posts, now()->addDay());
});
  1. File Handling:
$file = tap(new UploadedFile(), function($file) {
    Storage::disk('public')->put('path/to/file', $file);
    event(new FileUploaded($file));
});

Best Practices

  1. Use tap when you need to perform side effects without breaking the chain
  2. Consider tap for cleaner testing code
  3. Combine with arrow functions for more concise syntax
  4. Use collection's tap method when working with collections

Conclusion

The tap helper is a powerful tool for writing cleaner, more maintainable code in Laravel. It's particularly useful for performing side effects while maintaining a fluent interface in your code.

For more information, check out the Laravel documentation.


I have recently been doing some updates to a website I created and had the need to alter the diffForHumans output that carbon provides to a laravel models created at time. Found this pretty interesting and thought I would share.

The system is a listing portal where you are either wanting to buy something other people have listed or alternatively you can list an item you would like to sell.

Difference for humans
Listing::first()->created_at
// => Illuminate\Support\Carbon @1667281103 {#4822
//      date: 2022-11-01 05:38:23.0 UTC (+00:00),
//    }

Listing::first()->created_at->diffForHumans();
// => "10 minutes ago"

Listing::first()->created_at->diffForHumans([
    'parts' => 1
]);
// => "10 minutes ago"

>>> Listing::first()->created_at->diffForHumans([
    'parts' => 2
]);
// => "10 minutes 36 seconds ago"

Listing::first()->created_at->diffForHumans([
    'parts' => 2,
    'join' => ' and '
]);
// => "10 minutes and 36 seconds ago"

I hope you find the above as usefull as I have. To find out more head over to nesbot carbon difference for humans and see how you can use it in your project.