Laravel Concat Items of the Collection Example

Nov 18, 2022 . Admin



Hello Friends,

Here, I will show you how to work laravel concat items of the collection example. if you want to see a laravel collection concat example then you are in the right place. you can see the laravel collection merge example. you can understand the concept of how to concat multiple columns in laravel. Let's get started with concatenate collections laravel.

You can use this example with the versions of laravel 6, laravel 7, laravel 8, and laravel 9.

Count Syntax:
$collecton->concat(

    Array OR Collection

);

You have just to follow the below step and you will get the layout as below:

Step 1: Install Laravel

This is optional; however, if you have not created the laravel app, then you may go ahead and execute the below command:

composer create-project laravel/laravel example-app
Step 2: Create Format Route web.php
<?php

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\ConcatController;

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/

Route::get('/index',[ConcatController::class, 'index']);
Step 3: create ConcatController

we will create ConcatController. so you can see the below code with output:

php artisan make:controller ConcatController
App\Http\Controllers\ConcatController
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class ConcatController extends Controller
{
    /**
     * The attributes that are mass assignable.
     *
     * @var array
    */
    public function index()
    {
        $collectionA = collect(["One"]);
        
        $collectionB = collect(["Two"]);
        
        $collectionC = collect(["Three"]);
      
        $collection = $collectionA->concat($collectionB)->concat($collectionC);
            
        dd($collection);
    }
}
Step 4: Start Development Server

Start the development server. Use the PHP artisan serve command and start your server:

php artisan serve

Now you are ready to run our example so run the below command to quick run.

http://localhost:8000/index
Output:
#items: array:3 [▼
    0 => "One"
    1 => "Two"
    2 => "Three"
]

I hope it can help you...

#Laravel