Nikunj V
Nikunj V

Reputation: 293

Laravel - toArray() vs getAttributes()

I am using laravel 6 and using eloquent join to display data from multiple tables.

Consider following code:

    $ToGetDefaultAddress 
    = TbPersonaddress::join('tb_cities AS TbCitie','TbCitie.n_CityId_PK', '=', 'tb_personaddresses.n_CityId_FK')
                    ->join('tb_counties AS TbCountie','TbCountie.n_CountyId_PK', '=', 'tb_personaddresses.n_CountyId_FK')
                    ->join('tb_states AS TbState', 'TbState.n_StateId_PK','=' ,'tb_personaddresses.n_StateId_FK')
                    ->select('tb_personaddresses.n_PersonAddressesId_PK','tb_personaddresses.n_PersonId_FK',
                    'tb_personaddresses.d_EffectiveDateFrom','tb_personaddresses.d_EffectiveDateTo',
                    'TbCitie.s_CityCode','TbCitie.s_CityName','TbCountie.s_CountyCode',
                    'TbCountie.s_CountyName','TbState.s_StateCode','TbState.s_StateName')->first();

                    dd("Actual output:::::",$ToGetDefaultAddress);

Actual output:enter image description here

As shown in the above code, I am storing this output in $ToGetDefaultAddress variable. Now for getting only the attributes data, both toArray() and getAttributes() returns me the same result.

For e.g:

$DefaultAddress = $ToGetDefaultAddress->toArray();

and

$DefaultAddress = $ToGetDefaultAddress->getAttributes();

returns me the same output as shown below: enter image description here

My question is, what is the difference between using toArray() and getAttributes() ? Which one is recommended ? When to use toArray() and when to use getAttributes() ?

Upvotes: 5

Views: 11882

Answers (2)

Malkhazi Dartsmelidze
Malkhazi Dartsmelidze

Reputation: 4992

Let's look at source code:

If you look at them you will see that toArray() method returns full model with relationships and attributes and getAttributes() returns only model attributes (usually only columns).

This is code fragment from laravel source code:

    /**
     * Convert the model instance to an array.
     *
     * @return array
     */
    public function toArray()
    {
        return array_merge($this->attributesToArray(), $this->relationsToArray());
    }

I saw one method in source code which I didn't know. You can test it too: ->attributesToArray()

Upvotes: 7

Sehdev
Sehdev

Reputation: 5672

As per Laravel Documentation:

To convert a model and its loaded relationships to an array, you should use the toArray method. This method is recursive, so all attributes and all relations (including the relations of relations) will be converted to arrays:

$user = App\User::with('roles')->first();

return $user->toArray();

Laravel API -> Model -> method_getAttributes

getAttributes(): Get all of the current attributes on the model.

Laravel -> Eloquent: Serialization-> Serializing To Arrays

Upvotes: 1

Related Questions