如何在Laravel中使用Getter Setter方法?如何使用雄辩模型添加字段?

如何在Laravel中使用Getter Setter方法?如何使用雄辩模型添加字段?,laravel,Laravel,这是我的User.php模型 <?php namespace App; use Illuminate\Notifications\Notifiable; use Illuminate\Foundation\Auth\User as Authenticatable; class User extends Authenticatable { use Notifiable; /** * The attributes that are mass assignabl

这是我的User.php模型

<?php

namespace App;

use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable
{
    use Notifiable;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'firstname','lastname', 'email','image', 'password',
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];
}
我只想使用getter setter方法和雄辩的模型获得url的完整路径

<?php

namespace App;

use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable
{
    use Notifiable;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'firstname','lastname', 'email','image', 'password',
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];
}
像这样

Array
(
    [0] => Array
        (
            [id] => 1
            [firstname] => admin
            [lastname] => Gomez
            [email] => admin@admin.com

            [image] => public/images/admin.png

            [created_at] => 2019-11-10 04:30:01
            [updated_at] => 2019-11-10 14:03:38
        )

)
我还想添加另一个字段,如fullname(如[fullname]=>AdminGomez)

我也想要这个

Array
(
    [0] => Array
        (
            [id] => 1
            [firstname] => admin
            [lastname] => Gomez
            [email] => admin@admin.com
            [image] => admin.png
            [created_at] => 2019-11-10 04:30:01
            [updated_at] => 2019-11-10 14:03:38

            [fullname] => admin gomez
        )

)

谢谢

请在您的模型中定义这两种方法:

protected $append = ['full_name'];

/**
 * Get the user's full name.
 *
 * @return string
 */
public function getFullNameAttribute()
{
    return "{$this->first_name} {$this->last_name}";
}

/**
 * Get full image path
 *
 * @return string
 */
public function getImageAttribute()
{
    if ($this->image) {
        return public_path($this->image);
    }

    return '';
}

用户模型上图像的getter如下所示:

public function getImageAttribute()
{
    return public_path('images') . $this->image;
}
全名应该是文档中的内容,减去您案例中的下划线:

public function getFullNameAttribute()
{
    return "{$this->first_name} {$this->last_name}";
}
如果你想弄清楚它是如何工作的或者为什么工作的,那是因为Laravel使用了PHP的神奇方法。在这种情况下uuu得到。因此,模型基本上会查找任何get,如果存在,则使用“getFieldNameAttribute”方法