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

Eloquent Repository Laravel Package

richan-fongdasen/eloquent-repository

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require richan-fongdasen/eloquent-repository
    

    Publish the config (if needed):

    php artisan vendor:publish --provider="RichanFongdasen\EloquentRepository\RepositoryServiceProvider"
    
  2. Define a Repository Create a repository class (e.g., app/Repositories/UserRepository.php):

    namespace App\Repositories;
    
    use RichanFongdasen\EloquentRepository\EloquentRepository;
    use App\Models\User;
    
    class UserRepository extends EloquentRepository
    {
        public function model()
        {
            return User::class;
        }
    }
    
  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 the repository into a controller/service and use basic CRUD:

    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();
            return view('users.index', compact('users'));
        }
    }
    

Implementation Patterns

Core Workflows

  1. Basic CRUD Operations

    // Fetch all records
    $users = $userRepository->all();
    
    // Find by ID
    $user = $userRepository->find(1);
    
    // Create
    $user = $userRepository->create(['name' => 'John']);
    
    // Update
    $user = $userRepository->update(1, ['name' => 'Updated John']);
    
    // Delete
    $userRepository->delete(1);
    
  2. Query Scoping Define custom scopes in the repository:

    public function activeUsers()
    {
        return $this->scopeQuery(function ($query) {
            return $query->where('active', true);
        })->all();
    }
    
  3. Relationship Handling Use with() for eager loading:

    $user = $userRepository->find(1, ['posts']);
    
  4. Transactions Wrap operations in a transaction:

    $userRepository->transaction(function ($repository) {
        $user = $repository->create(['name' => 'Alice']);
        $user->posts()->create(['title' => 'Hello']);
    });
    

Integration Tips

  • Dependency Injection: Prefer constructor injection for repositories.
  • 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 model() method returns the fully qualified class name (e.g., App\Models\User).

    • return 'User'; (fails)
    • return User::class; (works)
  2. Query Caching Avoid caching raw queries without a TTL (Time-To-Live) to prevent stale data:

    // Bad: No TTL
    $this->scopeQuery(function ($query) {
        return $query->remember(60); // Unsafe!
    });
    
    // Good: With TTL
    $this->scopeQuery(function ($query) {
        return $query->remember(60 * 5); // 5 minutes
    });
    
  3. Mass Assignment Risks Use $fillable or $guarded in your model to prevent mass assignment vulnerabilities when using create() or update().

  4. Transaction Rollbacks Unhandled exceptions in transaction() will silently roll back. Use try-catch:

    try {
        $userRepository->transaction(...);
    } catch (\Exception $e) {
        // Log or handle the error
    }
    

Debugging Tips

  • Query Logging: Enable Laravel’s query logging to inspect generated SQL:
    \DB::enableQueryLog();
    $users = $userRepository->all();
    \Log::info(\DB::getQueryLog());
    
  • Repository Events: Override boot() to add listeners:
    protected static function boot()
    {
        static::created(function ($model) {
            \Log::info("Created: " . $model->name);
        });
    }
    

Extension Points

  1. Custom Methods Extend the repository with domain-specific methods:

    public function searchByEmail($email)
    {
        return $this->scopeQuery(function ($query) use ($email) {
            return $query->where('email', 'like', "%{$email}%");
        })->first();
    }
    
  2. Repository Interfaces Define interfaces for better testability and loose coupling:

    interface UserRepositoryInterface {
        public function find(int $id);
        public function all();
    }
    
  3. Dynamic Scopes Use traits or mixins to share query logic across repositories:

    trait SoftDeletesScope {
        public function withTrashed()
        {
            return $this->scopeQuery(function ($query) {
                return $query->withTrashed();
            });
        }
    }
    
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.
cuci/prototurk-sdk-symfony
clementtalleu/easyadmin-markdown-bundle
codeflextech/permission-manager
karnoweb/livewire-datepicker
sayedenam/sayed-dashboard
milito/query-filter
apiboxsym/user-bundle
apiboxsym/health-check-bundle
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager