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 Findby Laravel Package

someonefamous/laravel-findby

Add dynamic finders to Eloquent models: call User::findByLastName('Smith') or User::findAllByFirstName('Bob') instead of where()->first()/get(). Works with any snake_cased field name via the FindBy trait.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Install the package:
    composer require someonefamous/laravel-findby
    
  2. Add the trait to your Eloquent model:
    use SomeoneFamous\FindBy\Traits\FindBy;
    
    class User extends Model
    {
        use FindBy;
    }
    
  3. Use the new methods in your code:
    $user = User::findByLastName('Smith'); // Single record
    $users = User::findAllByFirstName('Bob'); // Collection
    

First Use Case

Replace repetitive where()->first() or where()->get() calls with cleaner syntax:

// Before
$admin = User::where('role', 'admin')->where('status', 'active')->first();

// After
$admin = User::findByRole('admin')->findByStatus('active');

Implementation Patterns

Common Workflows

  1. Chaining Methods:

    $user = User::findByEmail('john@example.com')
                ->findByStatus('active')
                ->findByRole('admin');
    

    Note: Each findBy* call adds a where clause.

  2. Dynamic Field Lookups:

    $field = 'last_name';
    $value = 'Smith';
    $user = User::findBy($field, $value); // Equivalent to `findByLastName`
    
  3. Bulk Operations:

    $bobs = User::findAllByFirstName('Bob'); // Collection
    $activeUsers = User::findAllByStatus('active'); // Collection
    
  4. Integration with Existing Queries:

    $query = User::where('deleted_at', null);
    $query->findByLastName('Smith'); // Appends `where('last_name', 'Smith')`
    

Best Practices

  • Use for simple, direct lookups (e.g., findById, findByEmail). Avoid overusing for complex queries.
  • Prefer findBy* over findAllBy* when you expect a single result (returns null if not found).
  • Combine with orWhere for conditional logic:
    User::findByLastName('Smith')->orWhere('first_name', 'John');
    

Gotchas and Tips

Pitfalls

  1. Namespace Changes (v2.0.0+):

    • Older code using use SomeoneFamous\FindBy\FindBy; will fail. Update to:
      use SomeoneFamous\FindBy\Traits\FindBy;
      
  2. Method Name Collisions:

    • If your model has a method named findBySomething, the trait’s dynamic method will override it. Rename your method or use the explicit findBy($field, $value) syntax.
  3. Case Sensitivity:

    • The trait converts method names to snake_case (e.g., findByLastNamelast_name). Ensure your database columns match this convention.
  4. Performance:

    • Each findBy* call adds a where clause. For large datasets, chain methods carefully to avoid excessive query building:
      // Inefficient (multiple queries if not optimized)
      User::findByLastName('Smith')->findByFirstName('John');
      
      // Better (single query)
      User::where('last_name', 'Smith')->where('first_name', 'John')->first();
      

Debugging Tips

  • Check Generated SQL: Use Laravel’s query logging to verify the trait’s behavior:

    DB::enableQueryLog();
    $user = User::findByLastName('Smith');
    dd(DB::getQueryLog());
    
  • Override Dynamic Methods: If the trait’s dynamic method generation conflicts with your needs, disable it by adding this to your model:

    protected $disableFindByDynamicMethods = true;
    

    Then manually define methods like:

    public function scopeFindByCustomField($query, $value)
    {
        return $query->where('custom_field', $value);
    }
    

Extension Points

  1. Custom Scope Support: Extend the trait to support custom scopes:

    // In your model
    public function scopeFindByCustomScope($query, $value)
    {
        return $query->where('custom_column', $value)->orWhere('other_column', $value);
    }
    
  2. Modify Query Logic: Override the findBy method in your model to add logic:

    public function findBy($field, $value)
    {
        return $this->newQuery()->where($field, $value)->firstOrFail();
    }
    
  3. Add Validation: Validate input before querying:

    public function findByEmail($email)
    {
        if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
            throw new \InvalidArgumentException('Invalid email');
        }
        return $this->newQuery()->where('email', $email)->first();
    }
    
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.
craftcms/url-validator
directorytree/privacy-filter-classifier
directorytree/privacy-filter
datacore/hub-sdk
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony
develia/geo-bundle
dreamzy/livewire-charts
touchestate-sdk/php-sdk
22h/doctrine-garbage-collection-bundle
agtp/agtp-php
agtp/mod-php
splash/sonata-admin
splash/metadata
splash/openapi
splash/scopes
splash/toolkit
testo/output-teamcity
testo/bridge-symfony