SolvedCRUD Bug image field, store in fake field (store as base64, not path)


I try to store the path of an image in a fake field. And it converts it to "base64", it's a problem.
It works when I specify a field other than "extras" and I create my mutator.

As I have several images on my pages (I use PageManager for simple pages). I need to store a different number on each page, which is why I would like a "fake field" solution, it would keep it flexible.

I try to follow the solution given here by @tabacitu Laravel-Backpack/CRUD#400.

Whatever I do, if I try to store an image in "extras", it converts it to base64 and that bug and even with the following code

public function setImageAttribute($value, $attribute_name = 'image')
        $disk = "public_folder";
        $destination_path = "uploads/folder_1/subfolder_3";

        // if the image was erased
        if ($value==null) {
            // delete the image from disk

            // set null in the database column
            $this->attributes[$attribute_name] = null;

        // if a base64 was sent, store it in the db
        if (starts_with($value, 'data:image'))
            // 0. Make the image
            $image = \Image::make($value);
            // 1. Generate a filename.
            $filename = md5($value.time()).'.jpg';
            // 2. Store the image on disk.
            \Storage::disk($disk)->put($destination_path.'/'.$filename, $image->stream());
            // 3. Save the path to the database
            $this->attributes[$attribute_name] = $destination_path.'/'.$filename;

I try to have something dynamic, otherwise I could post only one entry per column in the DB.

@tabacitu has given information to try to solve this problem. But I can not create it correctly.

So, is there a way to store multiple images from different fields on the same page in a fake-field?

Thank you

PS : Sorry for my english.

26 Answers

βœ”οΈAccepted Answer

Hi everyone. Allow me to post this to this closed topic. It could be useful to someone.

Looking for a solution to @Jimmylet post I landed here. I finally managed to store image paths into a fake field. It's not the best solution, as I didn't rewrite the backpack code to add this functionality, but it works. I'm not sure it's a backpack bug, but it's just something the fake fields are not thought for. Nothing mentioned in the documentation though (whether it should work or shouldn't).

As far as I could guess, the moment in the store call stack where actual values are written into the fake fields is inside some of the backpack structure (Model.php). To modify that behavior I should override quite a lot of files, and I didn't want to mess them up. Not now. So, why previous comments didn't work for me:
The getters and setters like getSomeFieldAttribute don't work as we would expect for fake fields. They do work for actual fields in the table. If you try to do setExtrasAttribute and do there the image processing, it also doesn't work, as the extras field is at the same time a "protected $fake" field and a "protected $appends" field.

So, what I did is to surface to the controller itself and insert the following code into the update and create methods. The code basically checks for fields ending with _image, then stores images to disk, gets their filename, and replaces the fake field data (data:image) with the recently created filename. VoliΓ ! Don't pay attention to the specific code that you won't need. This code is mostly the part of the setImageAttribute function where images are processed for actual DB fields. The model keeps the getImageAttribute (second part of the code) with the getAttributeValueExtended trick to parse the value to store and read it json_decoded from the fake field.

In the controller:

public function update(UpdateRequest $request)

        $fields = array_keys(request()->all());
        foreach ($fields as $field) {
            if (Str::endsWith($field, 'image'))
                $request[$field] = $this->processImage($request, $field, 'extras');
        return parent::updateCrud($request);

     * Stores the actual image to disk and returns the stored filename. Deletes previous file from disk, if any.
     * @param $request
     * @param $attribute_name
     * @param null $store_in If not null, image is stored in a fake field
     * @return null|string
    private function processImage($request, $attribute_name, $store_in = null)
        $value = $request[$attribute_name];
        $prev_value = $this->crud->getCurrentEntry()->{$attribute_name};
        $type = 'pages';

        $destination_path = env('IMAGES_STORAGE_WRITE_PATH') . $type;

        // if the image was erased
        if ($value == null) {
            $value = null;

        // if a new image was loaded
        if (Str::startsWith($value, 'data:image')) {
            $image = \Image::make($value);
            switch ($image->mime()) {
                case 'image/png':
                    $extension = '.png';
                    $extension = '.jpg';
            $filename = $type . '_' . $attribute_name . '_' . md5($value.time()) . $extension;
            \Storage::disk(env('IMAGES_STORAGE_DISK'))->put($destination_path . '/' . $filename, (string)$image->stream());
            $value = $filename;

        return basename($value);

    private function deleteImage($value)
        $type = 'pages';
        if (!empty($value)) {
            $file = basename($value);
            $file_path = env('IMAGES_STORAGE_WRITE_PATH') . Str::plural($type) . '/' . $file;

In the model:

    public function getHeader1ImageAttribute()
        return $this->retrieveImage('header_1_image', 'extras');

    public function getHeader2ImageAttribute()
        return $this->retrieveImage('header_2_image', 'extras');

    public function getHomeCoverImageAttribute()
        return $this->retrieveImage('home_cover_image', 'extras');

    private function retrieveImage($attribute_name, $stored_in = null)
        $type = Str::snake(class_basename($this));
        $value = $this->getAttributeValueExtended($attribute_name, $stored_in);

        if ($value && Str::contains($value, '_default.')) {
            return env('IMAGES_STORAGE_READ_PATH'). '/' . $value;
        if ($value) {
            return env('IMAGES_STORAGE_READ_PATH') . Str::plural($type) . '/' . $value;

    private function getAttributeValueExtended($attribute_name, $stored_in = null)
        if ($stored_in) {
            if (isset(json_decode($this->{$stored_in})->{$attribute_name}))
                return json_decode($this->{$stored_in})->{$attribute_name};
            return null;

        return $this->{$attribute_name};

Hope this helps someone!

Related Issues:

CRUD [Feature] Ability to define any (nested) fields inside "table" field
I did something very similar to this implemented a field following the table field default and creat...
CRUD How to customize search query?
:-)) hi @nathanielks Glad to hear the package gave was a nice surprise to you Well ...
CRUD Concatenate two columns in list view
Here's what you can do to make your attribute show when enableAjaxTable() is present on your CRUD: A...
CRUD ReflectionException Class translator does not exist
It seems this has to do with calling trans() in config files which is apparently not possible in lar...
CRUD Pagination using AJAX
Hi guys I've just finished AJAX pagination Is this considered? Right now all rows are queried ...
CRUD Bug image field, store in fake field (store as base64, not path)
Hi everyone Allow me to post this to this closed topic It could be useful to someone Looking for a s...
CRUD Laravel Backpack FIlter Not Called
Thx that solved the problem for me: Solution (working for Laravel >= 5.5) Configure App\Http\Middlew...
CRUD Upload field type on edit required issue
I know this is a closed issue but I found this after searching for a solution for a similar issue I ...
CRUD Return with Validator errors
Hi @OSDDQD This has happened to me before for custom CRUD entities when I applied the web middleware...
ngx admin No PostCSS Config found with build:prod
Or you can create a file named postcss.config.js in root directory Just leave it empty or write the ...
react admin Error: Invariant failed: You should not use <Route> outside a <Router>
Just remember: Before using {Route} from 'react-router-dom' library just make sure you put <Route> i...
EasyAdminBundle Multiple file/images upload - OneupUploaderBundle
I got this to work with VichUploaderBundle Is there any possibility to manage upload multiple files?...
react admin ra-data-graphql-simple shows error when plugged to apollo-server
I also encountered the issue and actually that's not a bug of React Admin but a React Hook misuse :)...
AdminLTE Active menu item with multi level submenus
nice script but it is not valid where you took the class ul.level-1 from? πŸ˜„ AdminLTE doesn't use so...
ngx admin Add JWT automatically for every HTTP request
FYI if you are using this solution check out my other reply: #1375 (comment) I couldn't get this to ...
react admin display array with arrayField or other
I cannot comprehend why this has been essentially wontfixed There is nothing at all strange about an...
AdminLTE Sidebar menu treeview not working after redirection in Angular 4
This problem in Angular 6 and AdminLTE 3 was solved as follows: Note: I have a Sidebar component tha...
laravel filemanager Error when accessing /laravel-filemanager
In lfmhelpers.php line 335 replace the return with this: and in vendor/unisharp/laravel-filemanager/...
coreui free react admin template Deploy build to Nginx give error Uncaught SyntaxError: Unexpected token <
@thangnvse try this adding this into your nginx conf Step: npm run-script build Copy built files to ...
react admin Deprecated findDOMNode warning in StrictMode - originating from react-transition-group
Any timeline on this issue? We are using react-admin for an admin panel for our client and want to e...
AdminLTE How to remember the toggle state of the sidebar menu?
I've fixed the external Script with this is your 1 question answered :) i missed this on exporting i...
EasyAdminBundle Is there anything new to use translatable entities?
While preparing to upgrade to SF4 and Flex I had a go at this: Integrating KnpLabs/DoctrineBehaviors...
react admin Typescript declarations
Thanks I'll start writing types for next and post them in DefinitelyTyped Hi ...
react admin Pagination fails with *TypeError: onChangePage is not a function*
I think I found a workaround for the time being Using yarn in my package.json I added this resolutio...
react admin [RFC] Embedded Arrays using FieldArray
Nice! I think this could make it to the core But I'd prefer that subrecords are displayed as lines r...
Serenity Sum of column in Detail Dialog - Shown/calculated immediately in a field of Parent Dialog
Here is a sample for you for OrderDialog constructor: Replace Q.notifySuccess with form.MyField.valu...
ant design pro πŸ›[BUG] Login doesn't work properly if /api/currentUser route is protected
I can also confirm that I've been hit by this It's much simpler to reproduce also ...
Serenity How to implement TreeView by SlickGrid in Serenity
It took me an hour to figure out how to turn default EntityGrid (generated by sergen) to a Tree List...
EasyAdminBundle After manual deleting cache got error
Hello Hours debugging helps figure out what's going on How to reproduce: Step 1 Install profiler ...
Serenity Back to use of AD credentials
@Solabar sorry I didn't get a chance to update this Some dudes here have resolved their issues and w...
Serenity [Please Comment] Inquiry about switching to TypeScript
Here is some update and proof of concept for TypeScript / Saltaralle interop: In ts-experiments bran...
axios module How to set query params and message body?
No I don't mean the baseURL but the url path As an example let's say I have the following call: Axio...
axios module How to import module to external file
@lukasborawski I think the following solution is far more elegant So let's say that I'm using axios ...
october Reorder of records in relation
@canthis thank you very much the references you gave pointed me in the right direction and I was abl...
axios module baseURL settings do not take effect for axios
it worked for me adding require('dotenv').config() to the nuxt.config.js Version v5.1.0 Reproduction...
parse server Parse Live Query don't work on AWS elasticbeanstalk
I had this problem recently I am using amazon elastic beanstalk with the parse server and for the pa...
parse server useMasterKey in cloudCode not working as expected
Much like how Parse.User.current() is invalid in a node script because of the global nature so is Pa...
parse server MongoError: Transaction numbers are only allowed on storage engines that support document-level locking
+1 I had this error until I added retryWrites=false to my database uri. I updated my parse server in...
october [feature] Selectable Repeater field Groups
Feature is approaching completion You may test by cloning the October develop branch ...
python dotenv Does not load from current directory
I'm running into the same issue on my Ubuntu server with Python 2.7 (had no problems in my local env...
parse server Request.user undefined and no information in request
I figure it out why request.user is undefined when calling Cloud function I'm trying to access a use...
parse server v2.2.4 Deploy failing on Amazon Elastic Beanstalk
2.2.4 works for me (multiple deployments so far) This is my setup: It was failing for me first becau...
parse server How to deploy a scalable Parse LiveQuery Server?
Here is our way to setup scalable Parse LiveQuery server on Heroku Because there is one and only 'we...
axios module Loading url in SSR fails, while all works on client side
Another problem is that in SSR mode it's not making a direct request to the data server but calling ...
parse server Parse Server Unauthorized Error
After a few rounds of trials and failures I finally got it working Your answer did really help a lot...
october Add 3 and 4 column support in backend
No problem will rewrite the code now on that Done - updated code and doc's. Summary of the PR This i...
october Backend pages wont open for new administrators
@Morsusy2k it will That's why it's called monkey patch πŸ˜„ Don't think so I'll dig deeper to get this...
parse server [PROPOSAL/DISCUSSION] AWS DynamoDB support
for now most tests are passing for Parse.Query the falling tests are expected to fail because of the...
lumber Install forest-admin plugin fails: self signed certificate in certificate chain
Hi @Sorok-Dva thank you for contributing! πŸ‘ I just released Lumber a few minutes ago ...