How to use services and repository pattern in Laravel
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 .
⚙️ Service
A Service handles your business logic. It serves as a bridge between the controller and the repository. Services are responsible for processing data, applying business rules, and orchestrating operations using one or more repositories.
Key Responsibilities:
- Implementing business rules.
- Coordinating multiple repository calls.
- Handling logic that doesn’t belong in the controller or model.
📦 Repository
A Repository acts as a data access layer. It abstracts the logic of interacting with the database or any data source. Instead of writing raw queries or Eloquent logic inside controllers or services, you delegate that to a repository class.
Key Responsibilities:
- Fetching data from the database.
- Inserting, updating, or deleting records.
- Wrapping Eloquent models and queries for cleaner code.
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 .
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 .
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');
Now run your route and check whether it's working or not. If you encounter any errors such as "class not found" or "file not found," please double-check the namespace and class names in your service and repository files.
Ouput :
Thank you for reading this article 😊
For any query do not hesitate to comment 💬