ItSolutionStuff.com

Laravel Convert Collection to Array Example

By Hardik Savani β€’ April 16, 2024
Laravel

Hi Dev,

This post will give you an example of laravel convert collection to array. I would like to show you laravel convert collection to associative array. you will learn laravel convert eloquent collection to array. This post will give you a simple example of laravel convert resource collection to array. Alright, let’s dive into the steps.

Here, i will show you two simple example of how to onvert collection to array in laravel application. one simple convert collection object to array using toArray() and next example will eloquent resource to array using pluck() and toArray().

so, let's see simple examples. you can use this example in laravel 6, laravel 7, laravel 8, laravel 9, laravel 10 and laravel 11 versions.

Example 1:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class PostController extends Controller

{

/**

* Write code on Method

*

* @return response()

*/

public function index(Request $request)

{

$collection = collect([1, 2, 3]);

$arrayColection = $collection->toArray();

dd($collection, $arrayColection);

}

}

Output:

Example 2:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Models\User;

class PostController extends Controller

{

/**

* Write code on Method

*

* @return response()

*/

public function index(Request $request)

{

$users = User::query()->take(5)->get();

$usersArray = $users->toArray();

dd($users, $usersArray);

}

}

Output:

I hope it can help you...

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

β˜…

Laravel Collection map() Add Attribute Example

Read Now β†’
β˜…

Laravel Collection Check If Key Exists Example

Read Now β†’
β˜…

How to Convert Collection to JSON in Laravel?

Read Now β†’
β˜…

Laravel Collection Get Unique Values Example

Read Now β†’
β˜…

Laravel Collection Get First and Last Item Example

Read Now β†’
β˜…

Laravel Collection Sum Column Example

Read Now β†’
β˜…

Laravel Collection keys() Method Example

Read Now β†’
β˜…

Laravel Collection Forget | Remove Item from Collection Laravel

Read Now β†’
β˜…

Laravel Collection SortBy Tutorial with Examples

Read Now β†’
β˜…

Laravel Collection Merge | How to Merge Two Eloquent Collection?

Read Now β†’
β˜…

Laravel Collection Unique | Remove Duplicates from Collection Laravel

Read Now β†’
β˜…

Laravel Collection Search Method Example

Read Now β†’