Answer the question
In order to leave comments, you need to log in
Checking products for Laravel 5.3 tag?
Is there an easier way to check for the presence of a specific tag in a product?
My function:
$tag = Tag::where('slug', $tag)->first();
$tagId = $tag->tag_id;
$products = Product::get();
foreach ($products as $product)
{
if(isset($product->tags) && !empty($product->tags))
{
$productTags = $product->tags;
foreach (json_decode($productTags) as $value)
{
if($value == $tagId){
$products[] = $product;
}
}
}
}
return view('products/tag', compact('products'));
Answer the question
In order to leave comments, you need to log in
We have a bunch of ManyToMany.
https://laravel.com/docs/5.3/eloquent-relationship...
https://laravel.com/docs/5.3/eloquent-relationship...
json_decode
I advise you to use this package: LARAVEL-TAGS
This package has what you need:
//retrieving models that have any of the given tags
Product::withAnyTags(['tag1', 'tag2']);
//retrieve models that have all of the given tags
Product::withAllTags(['tag1', 'tag2']);
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question