DEV Community

Techsolutionstuff
Techsolutionstuff

Posted on • Originally published at techsolutionstuff.com

How To Search Comma Separated Values In Laravel

In this article, we will see how to search comma separated values in laravel. Here, we will find specific id from comma separated values and will get comma separated values from the table. Here, we will search comma separated values using FIND_IN_SET() function.

FIND_IN_SET() is a predefined function of PHP MySQL. Also, we will use FIND_IN_SET() with whereRow() of the laravel query builder for the laravel comma separated search example.

So, let's see how to find comma separated values in laravel 8, and get comma separated values in laravel.

First of all, we need to create 2 tables to find specific id from comma separated values. I have posts and tags tables on my website.

  1. In the posts table we have "ID", "name", "tag_id".

  2. In the tags table we have "ID", "name".

Here, we will find records that have ID "1" from the "tag_id" column of the posts table.

$search_id = 1;
$data = \DB::table("posts")
    ->select("posts.*")
    ->whereRaw("find_in_set('".$search_id."',posts.tag_id)")
    ->get();
Enter fullscreen mode Exit fullscreen mode

Read Also: Laravel 8 User Roles and Permissions Without Package


And you will get output like the below.

Illuminate\Support\Collection Object
(
    [items:protected] => Array
    (
        [0] => stdClass Object
            (
                [id] => 1
                [name] => post1
                [tag_id] => 1,2
            )

        [1] => stdClass Object
            (
                [id] => 2
                [name] => post2
                [tag_id] => 1
            )
    )
)
Enter fullscreen mode Exit fullscreen mode

You might also like:

Read Also: Bootstrap Session Timeout Example In Laravel

Top comments (1)

Collapse
 
timoye profile image
Timothy Soladoye