在我的 api 路由中,我调用此方法,该方法返回包含所有数据的集合。
public function getAllGames()
{
return $this->game->all();
}
Run Code Online (Sandbox Code Playgroud)
数据看起来像这样
[
{
"id": 1,
"title": "Dragonball",
"description": "asdasd",
"image": "db.png",
"release_date": "2018-03-28",
"release_status": 0,
"created_at": "2018-03-12 21:28:49",
"updated_at": "2018-03-12 21:28:49"
},
]
Run Code Online (Sandbox Code Playgroud)
我想以 64 进制字符串形式返回图像,而不是图像名称。
我创建了一个帮助程序类,其中包含将图像从路径转换为 Base 64 字符串的方法:
class ImageHelper {
public static function imageToBase64($path) {
$type = pathinfo($path, PATHINFO_EXTENSION);
$data = file_get_contents($path);
$base64 = 'data:image/' . $type . ';base64,' . base64_encode($data);
return $base64;
}
}
Run Code Online (Sandbox Code Playgroud)
现在我不确定是否必须修改集合,以便我的数据看起来像这样:
[
{
"id": 1,
"title": "Dragonball",
"description": "asdasd",
"image": "daoisdboi3h28dwqd..", // base64string
"release_date": "2018-03-28",
"release_status": 0,
"created_at": "2018-03-12 21:28:49",
"updated_at": "2018-03-12 21:28:49"
},
]
Run Code Online (Sandbox Code Playgroud)
当然,我有不止一项数据。
编辑
我尝试了下面的建议来使用访问器,但它不起作用我得到了一个
file_get_contents(): 文件名不能为空
错误
我的模态现在看起来像这样:
class Game extends Model
{
protected $table = 'games';
protected $fillable = [
'title', 'description', 'image', 'release_date', 'release_status'
];
protected $appends = ['imageString'];
public function getImageStringAttribute() {
$type = pathinfo($this->image, PATHINFO_EXTENSION);
$data = file_get_contents($this->image);
$base64 = 'data:image/' . $type . ';base64,' . base64_encode($data);
return $base64;
}
}
Run Code Online (Sandbox Code Playgroud)
在我的 ApiController 中我这样做:
class ApiController extends Controller
{
protected $game;
public function __construct(Game $game)
{
$this->game = $game;
}
# TODO
# return image as base64 string
public function getAllGames()
{
return $this->game->getImageStringAttribute();
}
}
Run Code Online (Sandbox Code Playgroud)
使用访问器:https ://laravel.com/docs/5.6/eloquent-mutators#defining-an-accessor
将其添加到您的模型中:
protected $appends = ['imageString'];
public function getImageStringAttribute() {
$type = pathinfo($this->image, PATHINFO_EXTENSION);
$data = file_get_contents($this->image);
$base64 = 'data:image/' . $type . ';base64,' . base64_encode($data);
return $base64;
}
Run Code Online (Sandbox Code Playgroud)