skip to Main Content

I want to create api using laravel for fetch image which are stored in database in blob format but getting this errors

public function show()
 {
   $product= Product::all();
   return response($product);
 }

details

enter image description here

enter image description here

errors

enter image description here

2

Answers


  1. Because your product->image contains bytes content, encoder from response can’t properly deserialise it.

    You can’t pass pure byte code in a json response, use some kind of casting, read in docs "Eloquent: Mutators & Casting"

    Ideally you should create a custom casting which will transform your blob data into a transportable form: base64, hex, whatever you like best.

    Here’s an example for you

    <?php
     
    namespace AppCasts;
     
    use IlluminateContractsDatabaseEloquentCastsAttributes;
     
    class Blob implements CastsAttributes
    {
        public function get($model, $key, $value, $attributes)
        {
            return base64_decode($value);
        }
     
        public function set($model, $key, $value, $attributes)
        {
            return base64_encode($value);
        }
    }
    
    
    ......
    
    use AppCastsBlob;
    
    
    class Product extends Model
    {
        protected $casts = [
            'image' => Blob::class,
        ];
    }
    
    Login or Signup to reply.
  2. the format of image column is binary. you need to encode it as base64 to use it.
    just you need is a getter. you can accomplish this using cast or simle accesser.

    accesser

    class Product extends Model
    {
        use HasFactory;
    
        public function getImageAttribute($value)
        {
            return 'data:image/png;base64,' . base64_encode($value);
        }
    
    }
    

    now you have the base64 format of image and can use it in src attribute of image element . or even you can store the base64 string in file system.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search