我具有使用访问器和变异器来加密模型值的特征:
trait Encryptable
{
public function getAttribute($key)
{
$value = parent::getAttribute($key);
if (in_array($key, $this->encryptable)) {
$value = Crypt::decrypt($value);
return $value;
} else {
return $value;
}
}
public function setAttribute($key, $value)
{
if (in_array($key, $this->encryptable)) {
$value = Crypt::encrypt($value);
}
return parent::setAttribute($key, $value);
}
}
评论模型
protected $fillable = ['content','user_id','commentable_id', 'commentable_type'];
protected $encryptable = [
'content'
];
CommentController
public function storePostComment(Request $request, Post $Post)
{
$this->validate($request, [
'content' => 'required',
]);
$comment = $post->comments()->create([
'user_id' => auth()->user()->id,
'content' => $request->content
]);
dd($comment->content);
//return new CommentResource($comment);
}
发生的情况是,当我通过return new CommentResource($comment);
时,我的评论内容已加密,但是dd($comment->content);
解密了我的评论内容。如何解密整个注释对象,以便可以在资源中输出它?
编辑注释资源
class CommentResource extends JsonResource
{
/**
* Transform the resource into an array.
*
* @param \Illuminate\Http\Request $request
* @return array
*/
public function toArray($request)
{
return [
'id' => $this->id,
'content' => $this->content,
'owner' => $this->owner,
];
}
}
因为$post->comments()->create()
将不会调用setAttribute
方法。
根据源代码,雄辩的生成器创建方法调用setRawAttributes
:
public function setRawAttributes(array $attributes, $sync = false)
{
$this->attributes = $attributes;
if ($sync) {
$this->syncOriginal();
}
return $this;
}
尝试覆盖此方法,如下所示:
public function setRawAttributes(array $attributes, $sync = false)
{
$new_attributes = [];
foreach($attributes as $key => $val) {
if (in_array($key, $this->encryptable)) {
$new_attributes[$key] = Crypt::encrypt($val);
} else {
$new_attributes[$key] = $val;
}
}
$this->attributes = $new_attributes;
if ($sync) {
$this->syncOriginal();
}
return $this;
}