Debug School

rakesh kumar
rakesh kumar

Posted on • Updated on

How to filter data using multiselect element of form

How to filter when request data in array and DB col is in json form

Assuming you have a Laravel route that handles the filtering and returns JSON data, here's a simplified example:

Create a Laravel route:

use App\Http\Controllers\YourController;

Route::get('/filter-data', [YourController::class, 'filterData'])->name('filter.data');
Enter fullscreen mode Exit fullscreen mode

Create a controller to handle the filtering:

class YourController extends Controller
{
    public function filterData(Request $request)
    {
        $selectedValues = $request->input('selectedValues');

        // Perform filtering logic based on $selectedValues
        $filteredData = YourModel::where(function ($query) use ($selectedValues) {
            foreach ($selectedValues as $socialSite) {
                // Assuming column name is 'socialsite' and it's in JSON format
                $query->orWhereJsonContains('socialsite', $socialSite);
            }
        })->get();

        return response()->json($filteredData);
    }
}
Enter fullscreen mode Exit fullscreen mode

data will store in a way

use Illuminate\Database\Eloquent\Model;

class YourModel extends Model
{
    protected $fillable = ['socialsite'];

    public function storeData()
    {
        // Data to be stored in JSON format
        $data = [
            'facebook' => 50,
            'twitter' => 30,
            'utube' => 80,
        ];

        // Encode the array into JSON format
        $jsonData = json_encode($data);

        // Store the data in the database
        YourModel::create([
            'socialsite' => $jsonData,
        ]);
    }
}
Enter fullscreen mode Exit fullscreen mode

Explanation

let's break down the given code and explain it in detail.

Assuming you have a model called YourModel with a column named socialsite in JSON format. The goal of the code is to filter records where the socialsite column contains any of the social sites specified in the $selectedValues array.

Here's the breakdown:

Closure Function:

function ($query) use ($selectedValues) {
    foreach ($selectedValues as $socialSite) {
        $query->orWhereJsonContains('socialsite', $socialSite);
    }
}
Enter fullscreen mode Exit fullscreen mode

This is an anonymous function (closure) passed as an argument to the where method. It accepts a query builder instance as $query and uses the $selectedValues array.

It iterates over each social site in $selectedValues and adds an orWhereJsonContains condition to the query builder. This means it will filter records where the socialsite JSON column contains any of the specified social sites.

Query Execution:

YourModel::where(...)->get();
Enter fullscreen mode Exit fullscreen mode

The where method is applied to the YourModel class, and the closure function is used to build the conditions for the query.

get() is then called to execute the query and retrieve the filtered records.

Now, let's consider an example:

Assuming you have the following data in your socialsite column:

Row 1: {"facebook": 50, "twitter": 30, "utube": 80}
Row 2: {"instagram": 20, "twitter": 30, "linkedin": 40}
Row 3: {"facebook": 60, "utube": 90, "pinterest": 10}
Enter fullscreen mode Exit fullscreen mode
And you have $selectedValues = ['facebook', 'twitter'].
Enter fullscreen mode Exit fullscreen mode

The code will filter the records based on the selected social sites, resulting in rows 1 and 2 being included in the $filteredData collection.

Output (simplified for clarity):

$filteredData = YourModel::where(function ($query) use ($selectedValues) {
    foreach ($selectedValues as $socialSite) {
        $query->orWhereJsonContains('socialsite', $socialSite);
    }
})->get();
Enter fullscreen mode Exit fullscreen mode
// Output
/*
[
    {"facebook": 50, "twitter": 30, "utube": 80},
    {"instagram": 20, "twitter": 30, "linkedin": 40},
    {"facebook": 60, "utube": 90, "pinterest": 10}]
*/
Enter fullscreen mode Exit fullscreen mode

Create the HTML with jQuery to handle multiselect and AJAX:
in ajax route how to take array data
how to load all data initially using jquery through append div id container
when we filter then display only filterd data through append div id container

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Filter Data with Multiselect and AJAX</title>
  <script src="https://code.jquery.com/jquery-3.6.4.min.js"></script>
</head>
<body>

<select multiple id="multiselect">
  <!-- Add your options here -->
  <option value="option1">Option 1</option>
  <option value="option2">Option 2</option>
  <option value="option3">Option 3</option>
</select>

<button id="filterButton">Filter Data</button>

<div id="resultContainer"></div>

<script>
  $(document).ready(function() {
    // Load all data initially
    loadData();

    $('#filterButton').on('click', function() {
      // Get selected values from multiselect
      var selectedValues = $('#multiselect').val();

      // Perform AJAX request to Laravel route
      $.ajax({
        url: '/filter-data',
        type: 'GET',
        data: { selectedValues: selectedValues },
        success: function(data) {
          // Handle the received data
          displayFilteredData(data);
        },
        error: function(error) {
          console.error('Error:', error);
        }
      });
    });

    function loadData() {
      // Perform AJAX request to get all data initially
      $.ajax({
        url: '/all-data',
        type: 'GET',
        success: function(data) {
          // Display all data initially
          displayFilteredData(data);
        },
        error: function(error) {
          console.error('Error:', error);
        }
      });
    }

    function displayFilteredData(data) {
      // Display the filtered data in the result container
      var resultContainer = $('#resultContainer');
      resultContainer.empty(); // Clear previous results

      if (data.length > 0) {
        // Loop through the data and display it
        data.forEach(function(item) {
          resultContainer.append('<p>' + item.name + '</p>'); // Adjust based on your model fields
        });
      } else {
        resultContainer.append('<p>No data found.</p>');
      }
    }
  });
</script>

</body>
</html>
Enter fullscreen mode Exit fullscreen mode

Make sure to replace placeholders such as YourModel and column_name with your actual model and column names. Adjust the HTML and jQuery code as needed based on your application structure and requirements.

Another way

public function yourControllerMethod()
{
    $filteredData = YourModel::where(function ($query) use ($selectedValues) {
        foreach ($selectedValues as $socialSite) {
            $query->orWhereJsonContains('socialsite', $socialSite);
        }
    })->get();

    return view('your_blade_file', compact('filteredData'));
}
Enter fullscreen mode Exit fullscreen mode

In your Blade file (your_blade_file.blade.php), use jQuery to append the data to a div container. Here's a simplified example:
html

<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Your Blade File</title>
</head>
<body>

<div id="dataContainer">
    <!-- Data will be appended here using jQuery -->
</div>

<script src="https://code.jquery.com/jquery-3.6.4.min.js"></script>
<script>
    $(document).ready(function () {
        // Get the data passed from the controller
        var filteredData = {!! $filteredData->toJson() !!};

        // Iterate over the data and append to the container
        $.each(filteredData, function (index, item) {
            var jsonString = JSON.stringify(item);
            $("#dataContainer").append('<div>' + jsonString + '</div>');
        });
    });
</script>

</body>
</html>
Enter fullscreen mode Exit fullscreen mode

Summary

How to filter when request data in array and DB col is in json form
Create the HTML with jQuery to handle multiselect and AJAX:
in ajax route how to take array data
how to load all data initially using jquery through append div id container
when we filter then display only filterd data through append div id container

Top comments (0)