Laravel - toArray() vs getAttributes()

Viewed 5335

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() ?

2 Answers

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()

Related