How to remove duplicate query?

Good evening.
There is a table:
Product category
Ratings
Products

Display a list of the best products

I've set the connection with ratings
class Cat extends Model
{
 public function topProducts($limit = 10)
{
 return $this->belongsToMany(Product::class, 'la_products_top', 'cat_id', 'product_id')
 ->orderBy('la_products_top.num', 'ASC')
->limit($limit);
}
}


Product category:
class Product extends Model{
 public function cat() {
 return $this->hasOne(Cat::class,'id', 'cat_id');
}
}


In the model of the goods we also have getImageSrcAttribute, which gives the address of the pictures
class Product extends Model{
 public function getImageSrcAttribute() { 
 return 'img/' . $this->cat->alias . '/' . $this->img;
}
}


The queried, the getter is already in view:
@foreach($cat->topProducts as $pr)
the <li>
 <img src="{{ $pr->imageSrc}}"> 
</li>
 @endforeach


The output is a bunch of duplicate requests for the category.
Yes, you can add with('cat') and reduce it to two queries. But the essence remains the same. I don't like that one and same data category, twitch twice..
Can you remember the url of the picture to form in the view, but I want that the url was formed in one place (if you don't have to change it in a pile vyuha).
March 20th 20 at 11:24
1 answer
March 20th 20 at 11:26
$this->cat replaced by a variable.
Ie
with('category')
in the problematic method
public function getImageSrcAttribute($category) { 
 return 'img/'.$category.'/'.$this->img;
}

In the view method to call
<img src="{{ $product->getImageSrcAttribute($product->category->name)}}">
Yes, I also had this idea. Received the error. in getAttribute, you cannot pass variables. Caused I really like this: <img src="{{ $product->imgSrc($cat->alias)}}">
In your example it is a challenge already and lost all of the method ease of use getters laravel.. - Cornell_Donnelly commented on March 20th 20 at 11:29
@kiel.Beierand which 2 duplicate request? With('cat') in this construction they should not be - elbert49 commented on March 20th 20 at 11:32
1st request receipt of the data category to a page (because the top is displayed on the category page)

2nd this same category is already in getImageSrcAttribute - Cornell_Donnelly commented on March 20th 20 at 11:35
@kiel.Beier, then write the category in a variable and replace her with a duplicate request - elbert49 commented on March 20th 20 at 11:38
@kiel.Beier, if the right field, you can walk Mapa
->get()
->map(function ($item, $index) use($category) {
 $item['image_url'] = $item->getImageUrl($category);
 return $item;
})

but I would call in the view - elbert49 commented on March 20th 20 at 11:41

Find more questions by tags Laravel