Laravel Return an Array Instead of a Collection

In this tutorial you will learn Laravel Return an Array Instead of a Collection example. By default when we use the all or get methods then its return object not array. If you want to get the array recrods instead of collection then you can follow the below examples;

In laravel we can use laravel toArray() and pluck() methods to get bulk array collection instead or object in laravel 5, laravel 6, laravel 7, laravel 8, laravel 9 application.

Example 1:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\User;

class UserController extends Controller
{
    public function index()
    {
        $users = User::get()->toArray();

        echo '<pre>'; print_r($users); die;
    }

}

Output:

Array
(
    [0] => Array
        (
            [id] => 1
            [name] => Test 1
            [email] => test001@gmail.com
            [email_verified_at] => 
            [created_at] => 2021-07-17T19:13:54.000000Z
            [updated_at] => 2021-07-17T19:13:54.000000Z
            [first_name] => Test
            [last_name] => Demo
        )

    [1] => Array
        (
            [id] => 2
            [name] => Test 2
            [email] => test002@gmail.com
            [email_verified_at] => 
            [created_at] => 2021-10-31T09:53:35.000000Z
            [updated_at] => 2021-10-31T09:53:38.000000Z
            [first_name] => Test
            [last_name] => Two
        )

)

Example 2:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\User;

class UserController extends Controller
{
    public function index()
    {
        $users = User::select('id', 'name')->get()->toArray();

        echo '<pre>'; print_r($users); die;
    }

}

Output:

Array
(
    [0] => Array
        (
            [id] => 1
            [name] => Test 1
        )

    [1] => Array
        (
            [id] => 2
            [name] => Test 2
        )

)

Example 3:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\User;

class UserController extends Controller
{
    public function index()
    {
        $users = User::pluck( 'name', 'id' )->toArray();

        echo '<pre>'; print_r($users); die;
    }
}

Output:

Array
(
    [1] => Test 1
    [2] => Test 2
)

Leave a Comment