the_manish_sharma's avatar

Show Subcategory ON Images Blade Page

I want to show the same category's All subcategory on my images page. But when I am using foreach loop then Showing all subcategory views is happening.

Subcategory Database- id, categories_id

Images Database

id, categories_id, subcategories_id

  @foreach( App\Models\SubCategories::where('categories_id', '=', 'images_id')->get() as $subcategories )
      <?php 
        if( $subcategories->thumbnail == '' ) {
          $_image = 'default.jpg';
        } else {
          $_image = $subcategories->thumbnail;
        }
      ?>     
      <li class="slide">
        <a class="slink sq" href="{{ url('s',$subcategories->slug) }}">
          <img height="80" width="102" loading="lazy" class="img-circle sqtags" src="{{asset('public/img-category')}}/{{ $_image }}">
          <div class="sidekro chapta">
            <p>{{ $subcategories->name }}</p>
          </div>
        </a>
      </li>
    @endforeach`
0 likes
1 reply
tykus's avatar

What's this constraint where('categories_id', '=', 'images_id')?

Aside from that, put everything in its right place.

Data needed by the view should be organized in the Controller action, and passed to the view rather than making Eloquent queries in the view template:

// controller action 
$subcategories = SubCategories::where('categories_id', '=', 'images_id')->get(); // where clause means what?

Make an accessor method for computed properties on a Model instance. Here we will create an image computed property on each model instance:

// Model class
public function getImageAttribute()
{
    return $this->thumbnail ?? 'default.jpg';
}

This greatly simplifies the view template - it is concerned only with presentation now:

 @foreach($subcategories as $subcategory)
  <li class="slide">
    <a class="slink sq" href="{{ url('s',$subcategory->slug) }}"> <!-- is this correct -->
      <img 
          height="80"
          width="102" 
          loading="lazy" 
          class="img-circle sqtags" 
          src="{{asset('public/img-category/' . $subcategory->image) }}"
        >
      <div class="sidekro chapta">
        <p>{{ $subcategory->name }}</p>
      </div>
    </a>
  </li>
@endforeach

Please or to participate in this conversation.