How to Convert Object to Array in Laravel?

By Hardik Savani April 16, 2024 Category : Laravel

Hi Friends,

This simple article demonstrates of how to convert object to array in laravel. you'll learn laravel convert object to array. This example will help you laravel object to array. you will learn laravel eloquent object to array. Let's see below example convert object to array laravel.

You can use this example with laravel 6, laravel 7, laravel 8, laravel 9, laravel 10 and laravel 11 versions.

If you require to convert object data from db into array then you can do it using DB facade and Model Eloquent. Sometimes we need to give array data only so we must get array data from db. I have two examples so it can helps you.

Example 1:

In first example, If you use Model Eloquent for get data from database then you can do it using toArray(). toArray() will help to convert object into array data. So let's see bellow example and check it.

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Models\Product;

class ProductController extends Controller

{

/**

* Write code on Method

*

* @return response()

*/

public function index(Request $request)

{

$products = Product::select("*")

->get();

$data = $products->toArray();

dd($data);

}

}

Example 2:

In this example, if you use DB facade for getting data then it's different from above because when i was try to convert object into array then i can't do using direct toArray() but i found solution how to do it. You can check bellow example.

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Models\Product;

use DB;

class ProductController extends Controller

{

/**

* Write code on Method

*

* @return response()

*/

public function index(Request $request)

{

DB::setFetchMode(\PDO::FETCH_ASSOC);

$products = Product::select("*")

->get();

$data = $products->toArray();

dd($data);

}

}

Example 3:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Models\Product;

class ProductController extends Controller

{

/**

* Write code on Method

*

* @return response()

*/

public function index(Request $request)

{

$products = Product::select("*")

->get();

$data = (array) $products;

dd($data);

}

}

I hope it can help you...

Tags :
Shares