Laravel 5 模型访问器方法不起作用

Laravel 5 Model Accessor Methods not working

我正在尝试根据我对文档的最佳解释编写一些访问器方法,但它们似乎不起作用。我正在尝试通过 API 调用在计划的 artisan 控制台命令中触发时解密我正在加密的属性。我有一个看起来像这样的模型:

 <?php namespace App;

use Carbon\Carbon;
use Illuminate\Database\Eloquent\Model;
use ET_Client;
use ET_DataExtension;
use ET_DataExtension_Row;
use Crypt;

//child implementation
class MasterPreference extends Model {

////these fields can be mass assigned
    protected $fillable = [
        //
        'SMS_OPT_IN',
        'EMAIL_OPT_IN',
        'CUSTOMER_NAME',
        'CUSTOMER_ID'
    ];

    protected $DE_Names = ['MasterPreferences', 'SubPreferences'];

    protected $results = '';


    //instantiate and replicate
    function __construct()
    {

    }


    /**
     * 
     *
     * @return $getResult
     */
    public function getData()
    {

    }


    /**
     * store to the Db
     */
    public function store($results)
    {

    }


    /**
     * decrypt CUSTOMER_ID
     * @param $value
     * @return mixed
     */
    public function getCustomerIdAttribute($value)
    {

        return Crypt::decrypt($value);
    }

    public function getAccountHolderAttribute($value)
    {
        return $value . 'testing';
    }

    /**
     * ecnrypt Customer ID
     *
     * @param $value
     */
    public function setCustomerIdAttribute($value)
    {
        $this->attributes['CUSTOMER_ID'] = Crypt::encrypt($value);
    }



}

正如您在上面看到的,我创建了 2 个访问器方法,一个用于名为 CUSTOMER_ID 的属性,另一个用于名为 ACCOUNT_HOLDER 的属性。当我在 MasterPreferencesController 的索引方法中存储 $all = MasterPreference::all() 和 dd($all) 时,这些属性没有改变。调用这些访问器方法还有其他步骤吗?他们不应该只是靠 Laravel 的魔力工作吗?

感谢您的帮助!我很困惑,无法在文档中找到它。

我的猜测是 Laravel 假定您的字段名称是小写的。例如,如果您的字段名称是 custome_id,它将正确更改它的值。

您也可以尝试以下方法:

public function getCustomerIdAttribute($)
{
    return Crypt::decrypt($this->attributes['CUSTOMER_ID']);
}

public function getCustomerIdAttribute($)
{
    return Crypt::decrypt($this->CUSTOMER_ID);
}

然后使用

访问该值
MasterPreference::find($id)->customer_id

不确定是否有效以及哪个有效。

让我们看看魔术哪里出了问题。

基础知识:

1) 您正在扩展 class Illuminate\Database\Eloquent\Model。您在 MasterPreference class 中声明的函数将覆盖名称匹配的父 class 的函数。

来源:http://php.net/manual/en/keyword.extends.php

问题:

MasterPreference class 有一个空的 __construct 函数。

这会覆盖 Illuminate\Database\Eloquent\Model__construct() 函数,即:

/**
 * Create a new Eloquent model instance.
 *
 * @param  array  $attributes
 * @return void
 */
public function __construct(array $attributes = array())
{
    $this->bootIfNotBooted();

    $this->syncOriginal();

    $this->fill($attributes);
}

访问器和修改器的魔力就发生在这个代码漩涡中。

解决方法:

因此,MasterPreference__construct应该如下:

public function __construct(array $attributes = array())
{
     parent::__construct($attributes);
}