How to filter data on request in laravel 8?

  ajax, javascript, json, laravel, reactjs

I’ve in my React component this function:

const url = '/category';


function hideOnClick(id) {
  setHide({value: id})
  console.log(id);
  const body = {
      'chordId' : id,
  }

  const requestMetadata = {
      method: 'POST',
      headers: {
          'Content-Type': 'application/json'
      },
      body: JSON.stringify(body)
    };
    console.log(body);

  fetch(url, requestMetadata)
    .then(res => res.json())
    .then(res => {
        this.setState({
            url: res
        })
        console.log(res);
    })
}

In my route/web this line:

Route::post('/category', [PostController::class, 'postBody']);

And finally in my PostController this function

public function postBody(Request $request)
{
    $chord = $request->get('chordId');

    $posts = Post::join('categories', function ($builder) {
        $builder->on('categories.id', '=', 'posts.category_id');
    })
    ->where('name', '=', Str::before($chord, '.'))
    ->get();


    return view("posts.index-category")->with(array("posts" => $posts));
}

I have this graph dynamically rendered with categories and I want to make it interactive and used to filter posts based on where the user click on the graph.

Right now in my network tab I’m able to see the fetch request with a status of 200, and in the preview I see my view index-category with the correct posts, based on the filter in my PostController.

But I don’t know how to show this result in my page without a full page refresh. I think I’ve to use something like ajax but I don’t know how. Someone has any suggest?

Source: Laravel

Leave a Reply