Implementing CQRS (Command Query Responsibility Segregation) in Laravel 11

Websolutionstuff | Sep-30-2024 | Categories : Laravel

Hello, laravel web developers! In this guide, I'll show you how to implement CQRS (Command Query Responsibility Segregation) in Laravel 11. The idea behind CQRS is to split the responsibilities of handling data modification (commands) and data retrieval (queries).

This separation can improve the scalability and maintainability of your Laravel application. We'll use Laravel jobs for commands and custom query classes for queries. Let’s dive into a step-by-step example of how you can set up CQRS in your Laravel project!

Implementing CQRS (Command Query Responsibility Segregation) in Laravel 11

 

Step 1: Setting up the Laravel Project

First, make sure you have a Laravel 11 project set up. If you haven’t created one yet, you can install Laravel with the following command.

composer create-project --prefer-dist laravel/laravel cqrs-example

 

Step 2: Creating the Command (Write) Side

For the command side, we’ll use Laravel Jobs to handle any modifications to the data, like creating, updating, or deleting records.

Let’s create a job for adding a new user. Use the following command:

php artisan make:job CreateUserJob

This will create a job class in the app/Jobs directory. Now, let’s modify this job to handle the user creation logic.

namespace App\Jobs;

use App\Models\User;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Hash;

class CreateUserJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    public $userData;

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

    public function handle()
    {
        User::create([
            'name' => $this->userData['name'],
            'email' => $this->userData['email'],
            'password' => Hash::make($this->userData['password']),
        ]);
    }
}

In this example, the CreateUserJob will take the user data and create a new user.

 

Step 3: Dispatching the Command

You can use the following code in your controller or service to dispatch this job.

use App\Jobs\CreateUserJob;
use Illuminate\Http\Request;

class UserController extends Controller
{
    public function store(Request $request)
    {
        $userData = $request->only(['name', 'email', 'password']);
        CreateUserJob::dispatch($userData);

        return response()->json(['message' => 'User creation in process!'], 202);
    }
}

Here, we dispatch the CreateUserJob, which will be executed asynchronously, making the application more scalable.

 

Step 4: Creating the Query (Read) Side

We’ll create custom query classes for the query side to handle data retrieval. Let’s create a query class to get a list of users.

Create a folder named Queries inside the app directory. Inside this folder, create a file called UserQuery.php:

namespace App\Queries;

use App\Models\User;

class UserQuery
{
    public function getAllUsers()
    {
        return User::all();
    }

    public function getUserById($id)
    {
        return User::find($id);
    }
}

 

Step 5: Using the Query Classes

Now that we have our query class, we can use it in the controller to handle read operations.

use App\Queries\UserQuery;

class UserController extends Controller
{
    protected $userQuery;

    public function __construct(UserQuery $userQuery)
    {
        $this->userQuery = $userQuery;
    }

    public function index()
    {
        $users = $this->userQuery->getAllUsers();
        return response()->json($users);
    }

    public function show($id)
    {
        $user = $this->userQuery->getUserById($id);
        if ($user) {
            return response()->json($user);
        }
        return response()->json(['message' => 'User not found'], 404);
    }
}

In the controller, we are now using the UserQuery class for all read operations, separating the responsibility of fetching data from modifying it.

 

Step 6: Running the Application

Now that you have both the command and query sides set up, you can run the application to see how it works.

php artisan serve

You can create a user by sending a POST request to /users, and you can retrieve the list of users by sending a GET request to /users

 


You might also like:

Recommended Post
Featured Post
How To Import Large CSV File In Database Using Laravel 9
How To Import Large CSV File I...

In this article, we will see how to import a large CSV file into the database using laravel 9. Here, we will learn&...

Read More

Sep-15-2022

How To Install Tailwind CSS In Laravel 9
How To Install Tailwind CSS In...

In this article, we will see how to install tailwind CSS in laravel 9. Tailwind CSS works by scanning all of y...

Read More

Jun-13-2022

7 Easy Steps: Create Laravel 10 Livewire CRUD Operation
7 Easy Steps: Create Laravel 1...

Hey there! I'm diving into the world of Laravel 10 and Livewire, and I'm excited to share a step-by-step guide o...

Read More

Dec-06-2023

How To Install Angular In Ubuntu
How To Install Angular In Ubun...

In this article, we will see how to install angular in ubuntu. Angular is a framework, library, assets, a...

Read More

May-09-2022