Guides · Laravel
An Artisan command for Laravel repositories and services
The repository-service pattern means three new files for every model: an interface, a repository that implements it, and a service that uses it. Writing them by hand is tedious and easy to get slightly wrong. One custom Artisan command writes all three and tells you the line that wires them up.
gist.github.com/sawissac/e6f5dc58ce9467e0f9baa57d101c2484The pattern in one paragraph
Controllers stay thin and call a service, which holds the business rules. The service never touches Eloquent directly. It asks a repository interface for data, and Laravel's container hands it a concrete repository that does the querying. Because the service depends only on the interface, you can swap the repository for a fake in tests, or for a different data source later, without touching the service.
Controller → PostService → PostRepositoryInterface
↑ bound to
PostRepository → Eloquent / DBFor a Post model that's these files:
app/
├── Interfaces/PostRepositoryInterface.php
├── Repositories/PostRepository.php
├── Services/PostService.php
└── Providers/RepositoryServiceProvider.php ← binds the interfaceStep 1: a provider for the bindings
The bindings need a home. Create a dedicated provider:
php artisan make:provider RepositoryServiceProviderThis writes app/Providers/RepositoryServiceProvider.php. Laravel has to load it, and where you register it depends on the version:
- Laravel 11 and later:
make:provideradds it tobootstrap/providers.phpfor you. Nothing else to do. - Laravel 10 and earlier: add it to the
providersarray inconfig/app.phpyourself:
App\Providers\RepositoryServiceProvider::class,Step 2: the command
Generate an empty command class:
php artisan make:command MakeServiceRepoReplace the contents of app/Console/Commands/MakeServiceRepo.php with this:
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use Illuminate\Filesystem\Filesystem;
use Illuminate\Support\Str;
class MakeServiceRepo extends Command
{
protected $signature = 'make:service-repo {name : The model name, e.g. Post}';
protected $description = 'Create a repository interface, repository and service for a model';
public function handle(Filesystem $files): int
{
$name = Str::studly($this->argument('name'));
$variable = Str::camel($name).'Repository';
$targets = [
app_path("Interfaces/{$name}RepositoryInterface.php") => $this->interfaceStub(),
app_path("Repositories/{$name}Repository.php") => $this->repositoryStub(),
app_path("Services/{$name}Service.php") => $this->serviceStub(),
];
foreach ($targets as $path => $stub) {
$relative = Str::after($path, base_path().DIRECTORY_SEPARATOR);
if ($files->exists($path)) {
$this->components->warn("{$relative} already exists, skipped.");
} else {
$files->ensureDirectoryExists(dirname($path));
$files->put($path, str_replace(
['{{ name }}', '{{ variable }}'],
[$name, $variable],
$stub,
));
$this->components->info("{$relative} created.");
}
}
$this->line('Add this to RepositoryServiceProvider::register():');
$this->newLine();
$this->line(" \$this->app->bind(\\App\\Interfaces\\{$name}RepositoryInterface::class, \\App\\Repositories\\{$name}Repository::class);");
$this->newLine();
return self::SUCCESS;
}
private function interfaceStub(): string
{
return <<<'PHP'
<?php
namespace App\Interfaces;
interface {{ name }}RepositoryInterface
{
public function all();
public function find(int $id);
public function create(array $data);
public function update(int $id, array $data);
public function delete(int $id);
}
PHP;
}
private function repositoryStub(): string
{
return <<<'PHP'
<?php
namespace App\Repositories;
use App\Interfaces\{{ name }}RepositoryInterface;
use App\Models\{{ name }};
class {{ name }}Repository implements {{ name }}RepositoryInterface
{
public function all()
{
return {{ name }}::all();
}
public function find(int $id)
{
return {{ name }}::findOrFail($id);
}
public function create(array $data)
{
return {{ name }}::create($data);
}
public function update(int $id, array $data)
{
$model = $this->find($id);
$model->update($data);
return $model;
}
public function delete(int $id)
{
return $this->find($id)->delete();
}
}
PHP;
}
private function serviceStub(): string
{
return <<<'PHP'
<?php
namespace App\Services;
use App\Interfaces\{{ name }}RepositoryInterface;
class {{ name }}Service
{
public function __construct(
protected {{ name }}RepositoryInterface ${{ variable }},
) {}
}
PHP;
}
}A few details worth knowing:
- The stubs are nowdocs (
<<<'PHP', with quotes). PHP doesn't interpolate inside them, so$idand$dataare written out literally and only the{{ name }}placeholders change. The closingPHP;sets the indentation that gets stripped, so the generated files start at column zero. - The file names match the class names.
PostRepositorylives inPostRepository.php. Composer's PSR-4 autoloader finds classes by that rule, so a mismatch means a "class not found" error the first time the container resolves it. - Paths use forward slashes.
app_path("Repositories/...")works on macOS, Linux and Windows. Backslashes only work on Windows. - Existing files are skipped, never overwritten. Run it twice and the second run only prints warnings.
Str::studlynormalises the name, sopost,Postandblog_postgivePost,PostandBlogPost.
The repository stub assumes an Eloquent model with the same name in App\Models, and that its fields are in $fillable so create and update accept them. Edit the stubs to match how your project does it; that's the point of owning the command.
Laravel discovers commands in app/Console/Commands automatically, so there's nothing to register.
Step 3: generate and bind
php artisan make:service-repo Post INFO app/Interfaces/PostRepositoryInterface.php created.
INFO app/Repositories/PostRepository.php created.
INFO app/Services/PostService.php created.
Add this to RepositoryServiceProvider::register():
$this->app->bind(\App\Interfaces\PostRepositoryInterface::class, \App\Repositories\PostRepository::class);Paste the printed line into the provider:
<?php
namespace App\Providers;
use App\Interfaces\PostRepositoryInterface;
use App\Repositories\PostRepository;
use Illuminate\Support\ServiceProvider;
class RepositoryServiceProvider extends ServiceProvider
{
public function register(): void
{
$this->app->bind(PostRepositoryInterface::class, PostRepository::class);
}
}bind gives every consumer a fresh repository. singleton shares one instance for the whole request. Repositories that hold no state work either way, so bind is the safer default.
Using it
Put the business logic in the service:
class PostService
{
public function __construct(
protected PostRepositoryInterface $postRepository,
) {}
public function publish(int $id)
{
return $this->postRepository->update($id, [
'published_at' => now(),
]);
}
}And let the container inject the service into the controller:
class PostController extends Controller
{
public function __construct(
private PostService $posts,
) {}
public function publish(int $id)
{
return $this->posts->publish($id);
}
}Neither class creates anything with new. Laravel sees the type hints, builds PostService, notices it needs a PostRepositoryInterface, and uses the binding to supply a PostRepository.
In a test, swap the binding for a fake and the service never knows:
$this->app->bind(PostRepositoryInterface::class, FakePostRepository::class);Is it worth it?
Eloquent is already an abstraction over the database, so for a small CRUD app this pattern mostly adds files. It earns its keep when the business rules are big enough to want their own home, when you want to unit-test services without a database, or when some data comes from somewhere other than Eloquent: an external API, a cache, a search index.
If you do use it, use it consistently. The command makes that cheap: one line per model, and every model's files look the same.