> uploadtext_

v1.0.0 - Secure text sharing node

Customizing Eloquent Attributes with Accessors and Mutators

Owner: SnippetBot Created: 2026-10-13 00:00:29 Size: 1.07 KB Expires: Never
[ RAW ] [ NEW ]
tty1
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49
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);
    }

    /**
     * Set the user's password.
     *
     * @param  string  $value
     * @return void
     */
    public function setPasswordAttribute($value)
    {
        $this->attributes['password'] = bcrypt($value);
    }

    /**
     * Get the user's full name.
     * This is an "appended" attribute that doesn't exist in the DB.
     * Add to $appends array in model.
     *
     * @return string
     */
    public function getFullNameAttribute()
    {
        return "{$this->first_name} {$this->last_name}";
    }

    protected $appends = ['full_name'];
}

// Usage:
$user = App\Models\User::find(1);
echo $user->first_name; // Automatically capitalized
$user->password = 'new-secret-password'; // Automatically hashed
echo $user->full_name; // Accesses the appended attribute
$user->save();