Milind Daraniya

How to Search Comma Separated Values In Laravel with Example

Published July 21st, 2023 3 min read

Searching comma-separated values in Laravel can be a common requirement when dealing with data that is stored as a list of values within a single database column. In this tutorial, we will explore how to perform a search for specific values within a comma-separated list using Laravel's query builder.

 

Step 1: Setup the Database and Model

First, make sure you have a database table that contains the column with comma-separated values. For example, let's assume we have a "users" table with a "skills" column that stores skills as comma-separated values.

Next, create a corresponding model for the "users" table. You can generate the model by running the following command:

php artisan make:model User

 

Step 2: Perform the Search

In your controller or wherever you want to perform the search, you can use the where clause along with the LIKE operator to search for specific values within the comma-separated list. Here's an example:

use App\Models\User;
use Illuminate\Support\Facades\DB;

public function searchSkills($searchTerm)
{
    $users = User::where(DB::raw('FIND_IN_SET(?, skills)'), $searchTerm)
        ->get();

    return view('search-results', compact('users'));
}

 

In this example, we use the FIND_IN_SET function, available in most database systems, to find the position of the search term within the comma-separated list. The DB::raw method allows us to write raw SQL queries within Laravel's query builder.

The where clause checks if the search term is found within the "skills" column using the FIND_IN_SET function. If a match is found, the corresponding user will be included in the search results.

 

Step 3: Display the Results

Create a view file named search-results.blade.php to display the search results. Iterate over the $users collection to display the relevant information. For example:

<!-- search-results.blade.php -->
@foreach ($users as $user)
    <p>{{ $user->name }} - Skills: {{ $user->skills }}</p>
@endforeach

 

In this example, we display the user's name and their skills. Customize the output based on your specific requirements.