Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Ligonsker's avatar

How to return image blob (base64) and strings together from Controller to frontend?

I have an AJAX call that needs to get both array of data (strings) and an image base64 blob:

// From Controller
$data = [];
$details = Model::find($id);
$image = ModelImage::find($image_id);

$data['details'] = $details;
$data['image'] = $image;

return $data;

But I get the following error:

Malformed UTF-8 characters, possibly incorrectly encoded

So I even tried to do:

$data['image'] = mb_convert_encoding($image, 'UTF-8', 'UTF-8');

But then the error becomes:

Method Illuminate\Database\Eloquent\Collection::__toString() must return a string value

How can I return both values (details and blob) from controller then?

Thanks

0 likes
5 replies
Sinnbeck's avatar

Why is the image stored in the database? Store it on disk

2 likes
Tray2's avatar

I agree with @sinnbeck, binary files and large text files should be stored on disk, and not in the db.

1 like
Ligonsker's avatar

I'm not in charge of this specific DB unfortunately so I have to use it as it is now.

I even tried returning it from the Controller using

$data['image'] = base64_encode($image);

but I get the same error:

Method Illuminate\Database\Eloquent\Collection::__toString() must return a string value

Ligonsker's avatar

@Sinnbeck I ended up encoding in the controller and constructing the image src string in the controller then returning it back.

I also had a mistake where I tried to encode the collection object instead of the value of the base64 but now it's OK

Thank you!

Please or to participate in this conversation.