B
B
BonBon Slick2016-12-10 16:59:49
Laravel
BonBon Slick, 2016-12-10 16:59:49

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

3 answer(s)
A
Alexander, 2016-12-10
@BonBonSlick

We have a bunch of ManyToMany.
https://laravel.com/docs/5.3/eloquent-relationship...
https://laravel.com/docs/5.3/eloquent-relationship...

A
Alexander Aksentiev, 2016-12-10
@Sanasol

json_decode

If to make normally tags it will be possible to use whereHas.
And nothing good will come of it.

M
Mokhirjon Naimov, 2016-12-10
@zvermafia

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 question

Ask a Question

731 491 924 answers to any question