Michele Della Mea
Michele Della Mea

Reputation: 1002

how to save and retrieve base64 encoded data using Laravel model

I am doing a web app using Laravel 7 api. I receive data with a json request that I must store in the db with a base64 encoding. I store the data in this way:

public function create_request(Request $request)
    {
        $req_store = new Req;
        $req_store->text = base64_encode($request->input('requestInformations.text'));
        $req_store->save();
    }

Then obviously to retrieve the data of the text column I must use everytime base64_decode(). My question is that: is there a way to say to Laravel that everytime that I store a new request the column text must be authomatically encoded to base64 and everytime that I retrieve that data from the database the field text must be authomatically base64 decoded? I suppose I must write something in the Req.php model...

Can help?

Upvotes: 1

Views: 6527

Answers (2)

Shizzen83
Shizzen83

Reputation: 3529

You may use a custom caster

https://laravel.com/docs/7.x/eloquent-mutators#custom-casts

<?php

namespace App\Casts;

use Illuminate\Contracts\Database\Eloquent\CastsAttributes;

class Base64 implements CastsAttributes
{
    /**
     * Cast the given value.
     *
     * @param  \Illuminate\Database\Eloquent\Model  $model
     * @param  string  $key
     * @param  mixed  $value
     * @param  array  $attributes
     * @return mixed
     */
    public function get($model, $key, $value, $attributes)
    {
        return base64_decode($value);
    }

    /**
     * Prepare the given value for storage.
     *
     * @param  \Illuminate\Database\Eloquent\Model  $model
     * @param  string  $key
     * @param  array  $value
     * @param  array  $attributes
     * @return string
     */
    public function set($model, $key, $value, $attributes)
    {
        return base64_encode($value);
    }
}

And in your model

use App\Casts\Base64;
/**
     * The attributes that should be cast.
     *
     * @var array
     */
    protected $casts = [
        'text' => Base64::class,
    ];

Upvotes: 3

Shailesh Matariya
Shailesh Matariya

Reputation: 840

You should use Accessors & Mutators for this. Please follow the link https://laravel.com/docs/7.x/eloquent-mutators#accessors-and-mutators

public function getTextAttribute($value)
{
    return base64_decode($value);
}

public function setTextAttribute($value)
{
    $this->attributes['text'] = base64_encode($value);
}

Upvotes: 4

Related Questions