Hi Dev,Hi Artisan,
Now, let's see a tutorial of laravel convert collection to array. let’s discuss about laravel convert collection to associative array. I explained simply about laravel convert eloquent collection to array. If you have a question about laravel convert resource collection to array then I will give a simple example with a solution.
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()
so, let's see simple examples. you can use this example in laravel 6, laravel 7, laravel 8, laravel 9 and laravel 10 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...
Do you like below Tutorials ?
- Laravel 5.6 - Collection could not be converted to int
- Laravel - How to generate secure https URL from route?
- Laravel - Vue JS File Upload Example
- How to get last 7 days data in Laravel?
- Laravel Validation required if other field empty example
- Laravel Eloquent - When Case Statement in Select Query Example
- Laravel 7.x and 6.x Passing Variable to Javascript Example
- How to pass PHP variables in JavaScript or jQuery?