Laravel 8 映射類型轉(zhuǎn)換

2021-07-08 11:34 更新

有時候,你可能只需要對寫入模型的屬性值進行類型轉(zhuǎn)換而不需要對從模型中獲取的屬性值進行任何處理。一個典型映射類型轉(zhuǎn)換的例子就是 「hashing」。類型轉(zhuǎn)換類需要實現(xiàn) CastsInboundAttributes 接口,只需要定義 set 方法。

<?php

namespace App\Casts;

use Illuminate\Contracts\Database\Eloquent\CastsInboundAttributes;

class Hash implements CastsInboundAttributes
{
    /**
     * 哈希算法
     *
     * @var string
     */
    protected $algorithm;

    /**
     * 創(chuàng)建一個新的類型轉(zhuǎn)換類實例
     *
     * @param  string|null  $algorithm
     * @return void
     */
    public function __construct($algorithm = null)
    {
        $this->algorithm = $algorithm;
    }

    /**
     * 轉(zhuǎn)換成將要進行存儲的值
     *
     * @param  \Illuminate\Database\Eloquent\Model  $model
     * @param  string  $key
     * @param  array  $value
     * @param  array  $attributes
     * @return string
     */
    public function set($model, $key, $value, $attributes)
    {
        return is_null($this->algorithm)
                    ? bcrypt($value)
                    : hash($this->algorithm, $value);
    }
} 
以上內(nèi)容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號