ItSolutionStuff.com

GROUP_CONCAT with different SEPARATOR in Laravel Example

By Hardik Savani • April 16, 2024
Laravel MySql

Whenever, you need to use GROUP_CONCAT with differente separator(I mean default separator is ',', But you want to change '@','#','&' etc as you want). then you have to use use SEPARATOR keyword in GROUP_CONCAT(). If you are working on laravel then you have to also use DB::raw() for write GROUP_CONCAT() inside the this function.

So, Basically how to change seprator in group_concat(), In following example i change ',' separator into '@'.you can use the following example how to use in laravel 6, laravel 7, laravel 8, laravel 9, laravel 10 and laravel 11 versions.

Example:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Models\Item;

use DB;

class DemoController extends Controller

{

/**

* Write code on Method

*

* @return response()

*/

public function index(Request $request)

{

$items = Item::select(

"items.id",

"items.name",

DB::raw("(GROUP_CONCAT(items_city.name SEPARATOR '@')) as `cities`"))

->leftjoin("items_city","items_city.item_id","=","items.id")

->groupBy('items.id')

->get();

dd($items);

}

}

Try this.....

Tags: Laravel
Hardik Savani

Hardik Savani

I'm a full-stack developer, entrepreneur, and founder of ItSolutionStuff.com. Passionate about PHP, Laravel, JavaScript, and helping developers grow.

📺 Subscribe on YouTube

We Are Recommending You

How to use Carbon in Laravel Blade or Controller File?

Read Now →

Laravel Eloquent Group By Example

Read Now →

Laravel Eloquent Delete Record By ID Example

Read Now →

Laravel Eloquent whereNull() Query Example

Read Now →

How to use Union Query with Laravel Eloquent?

Read Now →

Laravel Eloquent Relationships Tutorial From Scratch

Read Now →

Laravel One to One Eloquent Relationship Tutorial

Read Now →

Laravel One to Many Eloquent Relationship Tutorial

Read Now →

Laravel Groupby Having with DB::raw() Example

Read Now →

Laravel Group By with Month and Year Example

Read Now →

Laravel Eloquent Group By with Multiple Columns Example

Read Now →

Laravel Select with Count Query with Group By Example

Read Now →