Add incremental custom attribute using Laravel model

307 Views Asked by At

I know how to add custom attribute using Laravel model. Does the same concept apply when we want to add incremental custom attribute as well?

/**Controller*/

$data = Model::select('*')->get(); //please ignore this line
            
//assuming that I want to append custom id & selected attribute to the model
$data->append('id')->toArray();         
$data->append('selected')->toArray();

/**Model*/

public function getSelectedAttribute()
{
    return false;
}

public function getIdAttribute()
{
    $increment = 0;
    $increment++;
    return $increment;
}

What I want to achieve: id value will be increment ( 0, 1, .. n+1)

Example :

[
   {
        "column": "value",
        "id": 0,
        "selected": false
    },
    {
        "column": "value",
        "id": 1,
        "selected": false
    }
]

What I got:

[
   {
        "column": "value",
        "id": 0,
        "selected": false
    },
    {
        "column": "value",
        "id": 0,
        "selected": false
    }
]

Any help is appreciated.

Edit. I used suggestion by Miqayel at this moment, and it works as intended.

static $increment = -13; // I need to change into -13 as the value starts on 13
$increment++;
return $increment;
0

There are 0 best solutions below