in this post, I will show you simple example of How to Convert an Array into Object in 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()`. You Can Learn Laravel Breeze Login with Google Auth Tutorials
How to Convert an Array into Object in Laravel Example
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" => "[email protected]"
];
$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
"[email protected]" // app/Http/Controllers/ImageController.php:28
I hope it can help you…