stepassia's avatar

Eloquent accessor

Hi, I've a model with a field named "idsTipoPatente". This is a string field in database with values like "10,11". I need to convert in an array.

I try with:

    protected $casts = [
        'idsTipoPatente' => 'array',
    ];

but return an empty attribute. I also try with this accessor:

    public function getIdsTipoPatenteAttribute($value) {
        //dummy return
    return "1"; 
    }

but return the same value ("10,11"). Whats wrong? Thanks a lot Stefano

0 likes
6 replies
d3xt3r's avatar

How are you accessing it ?

Check whether this is even being called ??

public function getIdsTipoPatenteAttribute($value) {
        dd($value);
    }
Hamelraj's avatar

@stepassla if you get your array then use for each loop you can get your array values

public function getIdsTipoPatenteAttribute($value) {
        foreach($valueas $val){
    return $val;
    }
acasar's avatar
acasar
Best Answer
Level 13

If you are not using snake_cased attributes, you should set $snakeAttributes property to false:

class YourModel extends Model 
{ 
    public static $snakeAttributes = false;
}
1 like
stepassia's avatar

Thanks to all, disabling snake case it's ok! Stefano

Karmody's avatar

Hi, I've got similar issue, but my attribute is starting from the capital letter as well. So code below is not working. I can't change sql-fields directly in DB, so need to manage it in the Laravel somehow.

class Cdr extends Model 
{ 
    public static $snakeAttributes = false;

// table field's examples: CHost, CSrcIP, CSrcNumberIn etc.


    public function getCHostAttribute($value)
    {
        return 'test';
    }

}

Please or to participate in this conversation.