Ad

Laravel Api Return Image As Base 64 String

- 1 answer

In my api route I call this method which Returns me a Collection with all data.

public function getAllGames()
{
    return $this->game->all();
}

The Data Looks like this

[
    {
        "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"
    },
]

Instead of the Image Name I would like to return the Image as a base 64 string.

I created a helper class which contains a method to convert an Image from a path to a base 64 string:

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;
    }

}

Now I am not sure have to modify the Collection so that my data Looks like this:

[
    {
        "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"
    },
]

Of Course I have more then one data.

Edit

I tried the suggesting below to use an accessor, but it did not work I got a

file_get_contents(): Filename cannot be empty

error

My modal Looks like this now:

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;
    }

}

And in my ApiController I do this:

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();
    }
}
Ad

Answer

Use an accessor: https://laravel.com/docs/5.6/eloquent-mutators#defining-an-accessor

Add this to your model:

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;
}
Ad
source: stackoverflow.com
Ad