Created
November 13, 2022 00:55
-
-
Save phpfour/4d20981ae66984229fb6f42191f6d420 to your computer and use it in GitHub Desktop.
Spatie Tag Custom Model
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php declare(strict_types=1); | |
namespace App\Models; | |
use ArrayAccess; | |
use Illuminate\Database\Eloquent\Builder; | |
class Tag extends \Spatie\Tags\Tag | |
{ | |
/** | |
* The attributes that are mass assignable. | |
* | |
* @var array | |
*/ | |
protected $fillable = [ | |
'name', | |
'slug', | |
'type', | |
'order_column', | |
'color', | |
'logo_url', | |
]; | |
public static function findFromSlug(string $slug, string $type = null, string $locale = null) | |
{ | |
$locale = $locale ?? static::getLocale(); | |
return static::query() | |
->where("slug->{$locale}", $slug) | |
->where('type', $type) | |
->first(); | |
} | |
protected static function convertSlugsToTags($values, $type = null, $locale = null) | |
{ | |
if ($values instanceof Tag) { | |
$values = [$values]; | |
} | |
return collect($values)->map(function ($value) use ($type, $locale) { | |
if ($value instanceof Tag) { | |
if (isset($type) && $value->type != $type) { | |
throw new \InvalidArgumentException("Type was set to {$type} but tag is of type {$value->type}"); | |
} | |
return $value; | |
} | |
$className = static::getTagClassName(); | |
return $className::findFromSlug($value, $type, $locale); | |
}); | |
} | |
public function scopeWithAnyTagsSlug( | |
Builder $query, | |
string | array | ArrayAccess | Tag $tags, | |
string $type = null, | |
): Builder { | |
$tags = static::convertSlugsToTags($tags, $type); | |
return $query | |
->whereHas('tags', function (Builder $query) use ($tags) { | |
$tagIds = collect($tags)->pluck('id'); | |
$query->whereIn('tags.id', $tagIds); | |
}); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment