How to Convert an Array into Object in Laravel?

By Hardik Savani December 9, 2024 Category : Laravel

in this post, I will show you simple example of how to convert an array to object in php laravel application.

In this example, we convert an array into an object using PHP's `(object)` typecasting. This allows us to access array keys as object properties, making the code simpler and more readable. We create a user array with `id`, `name`, and `email`, then retrieve these values from the object and display them using `dd()`.

Controller Code:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class DemoController extends Controller
{
    /**
     * Write code on Method
     *
     * @return response()
     */
    public function index(Request $request)
    {
        $userArray = [
            "id" => 1,
            "name" => "Hardik Savani",
            "email" => "hardik@gmail.com"
        ];

        $userObject = (object) $userArray;

        $id = $userObject->id;
        $name = $userObject->name;
        $email = $userObject->email;

        dd($id, $name, $email);
    }
}

Output:

1 // app/Http/Controllers/ImageController.php:28
"Hardik Savani" // app/Http/Controllers/ImageController.php:28
"hardik@gmail.com" // app/Http/Controllers/ImageController.php:28

I hope it can help you...

Tags :
Shares