How to Convert an Array into Object in 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...
Hardik Savani
I'm a full-stack developer, entrepreneur and owner of ItSolutionstuff.com. I live in India and I love to write tutorials and tips that can help to other artisan. I am a big fan of PHP, Laravel, Angular, Vue, Node, Javascript, JQuery, Codeigniter and Bootstrap from the early stage. I believe in Hardworking and Consistency.
We are Recommending you
- How to Manage User Timezone in Laravel?
- Laravel Get File Content from Request Object
- PHP Laravel Generate Apple Wallet Pass Example
- Laravel Breeze Login with Google Auth Example
- Laravel Datatables Relationship with Filter Column Example
- Laravel Datatables Date Format with created_at Example
- Laravel Eloquent Find with Trashed Record Example
- How to Read JSON File in Laravel?
- How to Set Custom Redirect URL After Login in Laravel Jetstream?
- Laravel Notify Flash Messages using Laravel Notify Example
- Laravel Relationship with Comma Separated Values Example
- Laravel Relationship with JSON Column Example
- Laravel 11 Display Image from Storage Folder Example