A Closer Look at Laravel's Service-Repository Setup

 How to use services and repository pattern in Laravel

Service-Repository architecture pattern - Laravel


Why we should use Service and Repository pattern :

While developing a small application we basically perform our CRUD operation in our controller , starting from database query to implementing business logic . For small application it is ok to write your code inside controller but in future due to client requirement you might need to grow the application functionality .

In such cases while developing a bigger application it will be very difficult to manage your codes present inside your controller , in that case service and repository architecture pattern will be very helpful .

In bigger application you need to make lots of API's where you have to send different success and error JSON responses and to manage all this service and repository architecture pattern is one of the best approach rather than writing your whole code inside your model .

There is no specific Laravel command to make service and repository , we have to make this manually .

I personally user this pattern because of the following reasons -
  • Code readability
  • Code reusability
  • Easy to manage codes
  • Easy to manage JSON responses while working with API's
  • You can distribute your codes like you can write your Database operations inside repository file and your other business logics inside service file .

File call flow :

The flow is very simple first call your service file from your controller and then call the repository file from the service file .

Service-Repositories architecture pattern - Laravel

Directory structure :

The directory structure is very simple as shown below .

  • create your service file as app\Services\file_name.php .
  • create your repository file as app\Repositories\file_name.php .

Service-Repositories architecture pattern - Laravel

Now let's create service and repository one by one and connect them . we will take an example for getting all the user data from database using service and repository pattern architecture .

Repository :

You can create your repository file anywhere inside your project but i will recommend to create a Repositories folder inside the app directory and create your repository file inside the Repositories folder like this app\Repositories\file_name.php .

app\Repositories\UserRepository.php :

<?php

namespace App\Repositories;

use App\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;

class UserRepository
{
    public function userRecord()
    {
        try{
            $user_data = User::all();
            return $user_data;
        }
        catch (\Exception $e) {
            Log::error(
                'Failed to fetch data'
            );
            return false;
        }

        
    }
}

Service :

Now create a Services folder inside app directory and create a service file inside your services directory like app\Services\file_name.php and call your repository as shown below .

app\Services\UserService.php :

<?php

namespace App\Services;

use App\Repositories\UserRepository;
use Illuminate\Support\Facades\Log;

class UserService
{
    protected $userRepository;

    public function __construct(UserRepository $userRepository)
    {
        $this->userRepository = $userRepository;
    }
    public function userRecord()
    {
        $user_data = $this->userRepository->userRecord();
        if ($user_data) {
            Log::info('List fetched successfully', ['method' => __METHOD__]);
            return response()->json(['response' => ['code' => 200, 'message' => 'List fetched successfully', 'data' => $user_data]]);
        } else {
            return response()->json(['response' => ['code' => 400, 'message' => 'Unable to fetch the list', 'data' => $list]]);
        }
    }
}

Controller :

Now it's time to call our service from our controller as shown below .

<?php

namespace App\Http\Controllers;

use App\Services\UserService;

class UserController extends Controller
{
    protected $userService;

    public function __construct(UserService $userService)
    {
        $this->userService = $userService;
    }
    public function userRecord()
    {
        return $this->userService->userRecord();
    }
}

web.php :

Route::get('/userrecord','UserController@userRecord')->name('userrecord');

That's now run your route and check whether it's working or not . If you are getting any error like class not found or file not found then please check your namespace and class name carefully inside your service and repository file .

Ouput :

Service-Repositories architecture pattern - Laravel


Previous Post Next Post

Contact Form