ItSolutionStuff.com

How to Convert an Array into Object in Laravel?

By Hardik Savani • December 9, 2024
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: Laravel
Hardik Savani

Hardik Savani

I'm a full-stack developer, entrepreneur, and founder of ItSolutionStuff.com. Passionate about PHP, Laravel, JavaScript, and helping developers grow.

📺 Subscribe on YouTube

We Are Recommending You

How to Manage User Timezone in Laravel?

Read Now →

Laravel Get File Content from Request Object

Read Now →

PHP Laravel Generate Apple Wallet Pass Example

Read Now →

Laravel Breeze Login with Google Auth Example

Read Now →

Laravel Datatables Relationship with Filter Column Example

Read Now →

Laravel Datatables Date Format with created_at Example

Read Now →

Laravel Eloquent Find with Trashed Record Example

Read Now →

How to Read JSON File in Laravel?

Read Now →

How to Set Custom Redirect URL After Login in Laravel Jetstream?

Read Now →

Laravel Notify Flash Messages using Laravel Notify Example

Read Now →

Laravel Relationship with Comma Separated Values Example

Read Now →

Laravel Relationship with JSON Column Example

Read Now →

Laravel 11 Display Image from Storage Folder Example

Read Now →