Laravel Convert Collection to Array Example
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...
Hardik Savani
I'm a full-stack developer, entrepreneur and owner of ItSolutionstuff.com. I live in India and I love to write tutorials and tips that can help to other artisan. I am a big fan of PHP, Laravel, Angular, Vue, Node, Javascript, JQuery, Codeigniter and Bootstrap from the early stage. I believe in Hardworking and Consistency.
We are Recommending you
- Laravel Collection map() Add Attribute Example
- Laravel Collection Check If Key Exists Example
- How to Convert Collection to JSON in Laravel?
- Laravel Collection Get Unique Values Example
- Laravel Collection Get First and Last Item Example
- Laravel Collection Sum Column Example
- Laravel Collection keys() Method Example
- Laravel Collection Forget | Remove Item from Collection Laravel
- Laravel Collection SortBy Tutorial with Examples
- Laravel Collection Merge | How to Merge Two Eloquent Collection?
- Laravel Collection Unique | Remove Duplicates from Collection Laravel
- Laravel Collection Search Method Example