Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

164
Views
Filtration data by category in Laravel

Index Controller

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

        return view('blog', compact('blogs', 'categories'));
    }

We have something like the following code on the blog page. First we get all the available categories, then a list of all blogs.

@extends('layouts.app')

@section('content')
<div class="container">
<div class="category-filter" id="filter">
     <div class="category-filter_item active">All</div>
     @foreach($categories as $category)
     <div class="category-filter_item">{{ $category->title }}</div>
     @endforeach
</div>

@foreach($blogs as $blog)
    <div class="blog-list {{ $blog->category_id}}">
        <h2 class="blog_title">{{ $blog->title }}</h2>
    </div>
@endforeach
</div>
@endsection

Can you please help to suggest a filtering function that, when choosing a specific category, will pull up all blogs from this category by ID?

JavaScript

document.querySelectorAll('.category-filter_item').forEach(el => {
  el.addEventListener('click', () => {
    document
      .querySelector('.category-filter_item.active')
      .classList.remove('active');
    el.classList.add('active');
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

You could use ajax in your case by sending an ajax request to your backend and you handle the data, then you return a response, this an example of a function in controller.

public function ajaxResponse(Request $request){
        if ($request->ajax()) {
            $cat_id = $request->input('cat');

            $blogs = Blog::query();
            if ($cat_id != null) {
                $blogs->whereHas("categories", function ($query) use ($cat_id) {
                    $query->whereIn('category_id', explode(',', $cat_id));
                })->get();
            }

            $blogs = $blogs->get();

            $blog = view('articles.ajaxblogs', ['blogs' => $blogs])->render();
        }
        return response()->json(['blog' => $blog]);
    }

Make sure to include category id in request.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!