Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Laravel Repository Laravel Package

sajadsdi/laravel-repository

Laravel repository pattern package to structure data access in your apps. Provides base repository classes, common CRUD methods, and an easy way to keep queries and persistence logic out of controllers and services for cleaner, testable code.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require sajadsdi/laravel-repository
    

    Publish the config (optional):

    php artisan vendor:publish --provider="Sajadsdi\LaravelRepository\LaravelRepositoryServiceProvider"
    
  2. Define a Repository Create a repository class (e.g., UserRepository) extending BaseRepository:

    namespace App\Repositories;
    
    use App\Models\User;
    use Sajadsdi\LaravelRepository\BaseRepository;
    
    class UserRepository extends BaseRepository
    {
        public function __construct(User $model)
        {
            parent::__construct($model);
        }
    }
    
  3. Register the Repository Bind the repository in a service provider (e.g., AppServiceProvider):

    $this->app->bind(
        \App\Repositories\UserRepository::class,
        \App\Repositories\UserRepository::class
    );
    
  4. First Use Case Inject and use the repository in a controller/service:

    use App\Repositories\UserRepository;
    
    class UserController extends Controller
    {
        protected $userRepository;
    
        public function __construct(UserRepository $userRepository)
        {
            $this->userRepository = $userRepository;
        }
    
        public function index()
        {
            $users = $this->userRepository->all(); // Basic query
            return view('users.index', compact('users'));
        }
    }
    

Implementation Patterns

Core Workflows

  1. CRUD Operations Leverage built-in methods for common queries:

    $user = $this->userRepository->find(1); // Find by ID
    $users = $this->userRepository->paginate(10); // Pagination
    $this->userRepository->create(['name' => 'John']); // Create
    $this->userRepository->update(1, ['name' => 'Jane']); // Update
    $this->userRepository->delete(1); // Delete
    
  2. Custom Scopes Define reusable query scopes in the repository:

    class UserRepository extends BaseRepository
    {
        public function scopeActive($query)
        {
            return $query->where('is_active', true);
        }
    
        public function getActiveUsers()
        {
            return $this->scopeActive()->get();
        }
    }
    
  3. Relationship Handling Use with() for eager loading:

    $users = $this->userRepository->with('posts')->get();
    
  4. Transactions Wrap operations in transactions:

    $this->userRepository->transaction(function ($repo) {
        $repo->create(['name' => 'Alice']);
        $repo->create(['name' 'Bob']);
    });
    

Integration Tips

  • Dependency Injection: Prefer constructor injection for repositories in services/controllers.
  • Service Layer: Use repositories in a service layer to decouple business logic from controllers.
  • Testing: Mock repositories in unit tests for isolated testing:
    $this->mock(UserRepository::class)->shouldReceive('find')->andReturn($user);
    

Gotchas and Tips

Pitfalls

  1. Model Binding Ensure the repository’s constructor matches the bound model exactly (e.g., User vs. App\Models\User). Use fully qualified names if needed.

  2. Overriding Base Methods Avoid redefining model() in child repositories unless extending functionality. Instead, use scopes or custom methods.

  3. Performance with Scopes Scopes are applied in the order they’re called. Chain them carefully to avoid unintended WHERE clauses:

    // Bad: Applies both scopes to the same query
    $this->scopeActive()->scopeAdmin()->get();
    
    // Good: Explicitly chain
    $this->scopeActive()->where('role', 'admin')->get();
    
  4. Transaction Isolation Nested transactions may fail silently. Use save() or create() within transactions instead of direct model persistence.

Debugging

  • Query Logging: Enable Laravel’s query logging to inspect generated SQL:
    \DB::enableQueryLog();
    $this->userRepository->all();
    \DB::getQueryLog();
    
  • Repository Events: Listen for repository events (e.g., retrieved, created) via:
    $this->userRepository->onRetrieved(function ($model) {
        logger($model);
    });
    

Extension Points

  1. Custom Base Repository Extend BaseRepository to add shared logic:

    class CustomBaseRepository extends BaseRepository
    {
        public function softDelete($id)
        {
            return $this->find($id)->delete();
        }
    }
    
  2. Dynamic Scopes Use addDynamicScope() to enable dynamic filtering:

    $this->userRepository->scopeByRole('admin')->get();
    
  3. Event Dispatching Trigger events after operations:

    $this->userRepository->afterCreate(function ($model) {
        event(new UserCreated($model));
    });
    
  4. API Resources Pair repositories with API resources for consistent JSON responses:

    return $this->userRepository->paginate(10)->resource();
    
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
codifyo/ts-generator-bundle
andydefer/laravel-cluster
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky
spatie/mailcoach-vapor