Search code examples
javascriptphplaravellaravel-5.3

Fetch records base on previous ID - Laravel


Please I want to fetch crops based on its category id, will be glad if this can be achieved without JavaScript

Display page

<div class="cat-list">
    <h3 class="cat-title">
        <a href="/filterByCategory/{{$category->cat_id}}">
            <i class="fa fa-car ln-shadow"></i>
            {{$category->cat_name}}<span class="count">{{$category->count()}}</span>
        </a>
        <span data-target=".cat-id-1" data-toggle="collapse" class="btn-cat-collapsed collapsed">
            <span class=" icon-down-open-big"></span>
        </span>
    </h3>
    <ul class="cat-collapse collapse in cat-id-1">
    @php
        $catID = $category->cat_id;
        //want to fetch crops base on the $catID and display in foreach
    @endphp
    </ul>
</div>

Controller function

public function index()
{
    $categories = Category::all();

    $crops = Crop::all();

    return view('public.index' , compact('categories' , 'crops'));
}

Crop Model

public function category() 
{ 
    return $this->belongsTo(Category::class, 'cat_id', 'crop_cat')
}

Category Model

public function category() 
{ 
    return $this->hasmany(Category::class, 'crop_cat','cat_id') 
}

Solution

  • You can add this method to your Category model:

    public function crops() {
        return $this->hasMany(Crop::class, 'catID');
    }
    

    and this function to your Crop model:

    public function category() {
        return $this->belongsTo(Category::class, 'catID');
    }
    

    After that you can basically loop through all categories on your blade template and in this loop echo out all crops of the current category. Then, this could look like this:

    @foreach ($categories as $category)
        {{ $category->name }}
    
        @foreach ($category->crops as $crop)
             {{ $crop->title }}
        @endforeach
    @endforeach
    

    You can find more information about Eloquent relationships on Laravel here.