3 Ways to Convert Objects to Arrays in Laravel

SHARE :

This simple article shows how to convert object to array in laravel. You will learn laravel to convert object to array. This example will help you to make laravel object into array. You will learn laravel eloquent object to array. Let's see below example convert laravel object to array.

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

If you need to convert object data from db to array then you can do it using DB facade and Eloquent Model. Sometimes we need to provide array data only so we have to get array data from db. I have two examples so that may help you.

Example One

In first example, If you are using Eloquent Model to get data from database then you can do it by using toArray(). toArray() will help convert the object into array data. So let's take a look at an example of bellows and check.

<?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 Two

In this example if you use DB facade to get data then it is different than above because when I try to convert object to array then I can't use direct toArray() but I found solution how to do it. You can check examples of bellows.

<?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 Three

<?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);
    }
}

OOKINFO

Jasa pembuatan Aplikasi Mobile dan Web. Siap memberikan solusi digital untuk bisnis anda. Tugas Kuliah, Organisasi, Perusahaan, E-Commerce.