TitasGailius / nova-search-relations

This package allow you to include relationship columns into Laravel Nova search query.
Other
351 stars 33 forks source link

Search with Spatie Translatable field #40

Open sezohessen opened 1 year ago

sezohessen commented 1 year ago

I need to search with translatable field

public static $searchRelations = [
        'category' => ['title'],
    ];

title has translatable property of Spatie package

public $translatable = ['title'];
anditsung commented 1 year ago

I need to search with translatable field

public static $searchRelations = [
        'category' => ['title'],
    ];

title has translatable property of Spatie package

public $translatable = ['title'];

create a new class that implements search im not using spatie package and dont know how it works.

this is an example how i search on laravel nova actions using moprh on the target

class MorphSearch implements Search
{
    /**
     * Searchable columns.
     *
     * @var array
     */
    protected $morphRelation;

    /**
     * Instantiate a new search query instance.
     *
     * @param array $columns
     */
    public function __construct(array $morphRelation)
    {
        $this->morphRelation = $morphRelation;
    }

    public function apply(Builder $query, string $relation, string $search): Builder
    {
        foreach ($this->morphRelation as $morphClass => $columns) {
            if (class_exists($morphClass) && is_subclass_of($morphClass, Model::class)) {
                $query->orWhereHasMorph($relation, [$morphClass], function ($query) use ($columns, $relation, $search) {
                    return (new ColumnSearch($columns))->apply($query, $relation, $search);
                });
            }
        }

        return $query;
    }
}

nova resource

...

public static function searchableRelations(): array
    {
        return [
            'target' => new MorphSearch([
                'App\Models\Role' => ['name'],
                'App\Models\User' => ['name', 'username', 'email'],
                'App\Models\Permission' => ['name'],
                'App\Models\Invite' => ['email'],
            ])
        ];
    }

...