---
# System prepended metadata

title: Laravel Eloquent ORM Accessor
tags: [Laravel]

---

# Laravel Eloquent ORM Accessor

```php=
<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class User extends Model
{
    /**
     * Get the user's first name.
     *
     * @param  string  $value
     * @return string
     */
    public function getFirstNameAttribute($value) // 駝峰式命名
    {
        return ucfirst($value);
    }
}
```

當我們嘗試檢索 `$user->first_name`， Eloquent 會自動調用 `getFirstNameAttribute($value`)。

```php=
$user = App\Models\User::find(1);

$firstName = $user->first_name;
```

[參考資料](https://laravel.com/docs/8.x/eloquent-mutators#defining-an-accessor)

###### tags: `Laravel`