How to Convert Object to Array in Laravel

Hello Geek,, In Laravel, there are several ways to convert an object to an array. Here are some of the methods you can use:

  1. Using the toArray() method:

This is the most common way to convert an object to an array in Laravel. The toArray() method is available on all Eloquent model instances, and it will convert the model’s attributes into an array. Here’s an example:

$user = User::find(1);
$array = $user->toArray();

In this example, we’re retrieving a user with an ID of 1 and then converting it to an array using the toArray() method.

  1. Using the json_decode() function:

Another way to convert an object to an array is to use the json_decode() function. This function takes a JSON string as its first parameter and returns an array. Here’s an example:

$user = User::find(1);
$json = json_encode($user);
$array = json_decode($json, true);

In this example, we’re encoding the user object as a JSON string using the json_encode() function, and then we’re decoding the JSON string back into an array using the json_decode() function.

  1. Using the get_object_vars() function:

The get_object_vars() function can also be used to convert an object to an array. This function takes an object as its parameter and returns an array of the object’s properties and their values. Here’s an example:

$user = User::find(1);
$array = get_object_vars($user);

In this example, we’re retrieving a user with an ID of 1 and then converting it to an array using the get_object_vars() function.

  1. Using the castAsArray() method:

Laravel 8 introduced a new feature called castAsArray() that allows you to define attributes on your models that should always be cast to an array. This means that any time you retrieve an instance of the model, these attributes will be returned as arrays rather than objects. Here’s an example:

class User extends Model
{
    protected $casts = [
        'settings' => 'array',
    ];
}

In this example, we’re defining a “settings” attribute on our User model that should always be cast as an array. Now, any time we retrieve a User instance, the “settings” attribute will be returned as an array.

These are the different methods to convert an object to an array in Laravel. Choose the one that works best for your particular situation.

Leave a Reply