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

Search Relations Laravel Package

titasgailius/search-relations

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require titasgailius/nova-search-relations
    

    Publish the config file (if needed):

    php artisan vendor:publish --provider="TitasGailius\NovaSearchRelations\NovaSearchRelationsServiceProvider"
    
  2. Basic Usage Add the HasSearchableRelations trait to your Nova resource:

    use TitasGailius\NovaSearchRelations\Traits\HasSearchableRelations;
    
    class Post extends Resource
    {
        use HasSearchableRelations;
    
        // ...
    }
    
  3. First Use Case Define a searchable relation in your resource:

    public static $searchableRelations = [
        'author', // Searches the 'author' relation (e.g., User)
        'tags',   // Searches the 'tags' relation (e.g., Tag)
    ];
    

    Nova will now allow searching related models directly from the index view.


Implementation Patterns

Workflows

  1. Searching Related Models

    • Use the built-in search input in Nova’s index view to filter related records.
    • Example: Search for posts where the author.name contains "John".
  2. Customizing Search Fields Override the searchableRelationFields method to specify which fields to search:

    public function searchableRelationFields($relationName)
    {
        return match($relationName) {
            'author' => ['name', 'email'],
            'tags' => ['name', 'slug'],
            default => [],
        };
    }
    
  3. Dynamic Relations Handle polymorphic or dynamic relations by extending the trait:

    public function resolveSearchableRelation($relationName, $query)
    {
        if ($relationName === 'comments') {
            return $query->whereHas('comments', fn($q) => $q->where('content', 'like', '%' . $this->search . '%'));
        }
    }
    
  4. Integration with Nova Actions Combine with Nova actions for bulk operations:

    public function fields(Request $request)
    {
        return array_merge(parent::fields($request), [
            (new Text)->onlyOnDetail(),
            (new HasSearchableRelations)->onlyOnIndex(),
        ]);
    }
    
  5. Eager Loading Optimize queries by eager-loading relations in the resolveForNavigation method:

    public static function resolveForNavigation($resource)
    {
        return $resource->load('author', 'tags');
    }
    

Gotchas and Tips

Pitfalls

  1. Performance Issues

    • Avoid searching large relations without proper indexing. Use database indexes on searchable fields.
    • Example:
      Schema::table('posts', function (Blueprint $table) {
          $table->index('author_id');
      });
      
  2. Case Sensitivity

    • Searches are case-sensitive by default. Use strtolower in custom queries:
      $query->whereRaw('LOWER(name) LIKE LOWER(?)', ['%' . $this->search . '%']);
      
  3. Circular Dependencies

    • Searching bidirectional relations (e.g., posts and comments) may cause infinite loops. Explicitly define one direction:
      public static $searchableRelations = ['posts']; // Only search posts, not comments
      
  4. Nova Caching

    • Clear Nova’s cache after adding new relations:
      php artisan nova:cache-clear
      

Tips

  1. Debugging Queries Enable Laravel query logging to inspect generated SQL:

    DB::enableQueryLog();
    // Run Nova request
    $queries = DB::getQueryLog();
    
  2. Customizing the Search UI Override the search blade template in resources/views/vendor/nova/search-relations/. Example:

    // app/Providers/NovaServiceProvider.php
    public function tools()
    {
        return [
            new \TitasGailius\NovaSearchRelations\NovaSearchRelations(),
        ];
    }
    
  3. Testing Use Nova’s HTTP tests to verify search functionality:

    $this->actingAs($user)
         ->get('/nova/resources/posts?search=John')
         ->assertSee('John');
    
  4. Extending Functionality Add support for soft-deleted relations by modifying the trait:

    public function scopeSearchableRelation($query, $relationName, $search)
    {
        return $query->whereHas($relationName, fn($q) => $q->where('name', 'like', '%' . $search . '%')->withTrashed());
    }
    
  5. Documentation Gaps

    • Check the GitHub issues for undocumented features or bugs.
    • Example: Some users report issues with nested relations (e.g., posts.tags.category).
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.
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle
atriumphp/atrium
sandermuller/package-boost-laravel
sandermuller/boost-skills
redaxo/core
yusufgenc/filament-api-forge
l3aro/rating-star-for-filament
leek/filament-subtenant-scope