I'm defining my class as such:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Foo extends Model
{
use HasFactory;
protected $fillable = [
'id', 'first_name'
];
public function getFirstNameAttribute($value = null)
{
return ucfirst($value);
}
}
Then I populate my DB with entry for that model:
\App\Models\Foo::create(['first_name' => 'foo']);
Then I'm calling accessor as follows:
\App\Models\Foo::first()->first_name;
=> "Foo"
which is expected
and
\App\Models\Foo::first()->firstName;
=> ""
which is unexpected (but understandable as even though getFirstNameAttribute method is being called, DB property firstName is being accessed and that doesn't exist)
I'd like to ensure that in both cases correct property (first_name) is being accessed.
Does this mean that ($value = null) is unreliable and one should always rely on $this->attributes['first_name']?
As such, this code becomes:
public function getFirstNameAttribute($value = null)
{
return ucfirst($this->attributes['first_name']);
}
Though I'd probably expect
>>> \App\Models\Foo::first()->first_____na______me;
=> "Foo"
to not do this.