MFirdausA's avatar

how trix editor save only attachment to other collumn in db

hi , i'm confused now. how to save only attachment to plan_attachment column from one input. currently i have 2 function in controller to save the attachment , upload and mom_attahcment. but, this function mom_attachment made for save to column plan_attachment

//my view

//upload public function upload(Request $request) { if ($request->hasFile('file')) { //get filename with extension $filenamewithextension = $request->file('file')->getClientOriginalName();

        //get filename without extension
        $filename = pathinfo($filenamewithextension, PATHINFO_FILENAME);

        //get file extension
        $extension = $request->file('file')->getClientOriginalExtension();

        //filename to store
        $filenametostore = $filename . '.' . $extension;

        Storage::delete('public/', $filename);

        //Upload File
        $request->file('file')->storeAs('public/', $filenametostore);

        // you can save image path below in database
        $path = asset('storage/public/mom-attachment/' . $filenametostore);

        echo $path;
        exit;
    }
}

public function mom_attachment(Request $request, $momid) { $mom = Mom::findOrFail($momid);

    if ($request->file('file')) {
        $attachment = $request->file('data-trix-attachment');
        $filename = $attachment->getClientOriginalName();
        $attachment->file('file')->storeAs('/public/mom-attachment/', $filename);
        $data['file']= $filename;

        $data= $mom->plan_attachment;
        $mom->save();
    }
}

//route

Route::post('/upload', ['uses' => 'App\Http\Controllers\MomController@upload', 'as' => 'upload']); Route::post('/mom-attachment/{momid}', ['uses' => 'App\Http\Controllers\MomController@mom_attachment', 'as' => 'mom.attachment']);

// attachment.js (function() { var HOST = uploadUrl; //pass the route

addEventListener("trix-attachment-add", function(event) {
    if (event.attachment.file) {
        uploadFileAttachment(event.attachment)
    }
})

function uploadFileAttachment(attachment) {
    uploadFile(attachment.file, setProgress, setAttributes)

    function setProgress(progress) {
        attachment.setUploadProgress(progress)
    }

    function setAttributes(attributes) {
        attachment.setAttributes(attributes)
    }
}

function uploadFile(file, progressCallback, successCallback) {
    var formData = createFormData(file);
    var xhr = new XMLHttpRequest();
     
    xhr.open("POST", HOST, true);
    xhr.setRequestHeader( 'X-CSRF-TOKEN', getMeta( 'csrf-token' ) );

    xhr.upload.addEventListener("progress", function(event) {
        var progress = event.loaded / event.total * 100
        progressCallback(progress)
    })

    xhr.addEventListener("load", function(event) {
        var attributes = {
            url: xhr.responseText,
            href: xhr.responseText + "?content-disposition=attachment"
        }
        successCallback(attributes)
    })

    xhr.send(formData)
}

function createFormData(file) {
    var data = new FormData()
    data.append("Content-Type", file.type)
    data.append("file", file)
    return data
}

function getMeta(metaName) {
    const metas = document.getElementsByTagName('meta');
   
    for (let i = 0; i < metas.length; i++) {
      if (metas[i].getAttribute('name') === metaName) {
        return metas[i].getAttribute('content');
      }
    }
   
    return '';
  }

document.addEventListener("trix-initialize", function(event) {
    var editorElement = event.target;
    if (editorElement.getAttribute("input") === "attendance") {
        var toolbar = editorElement.toolbarElement;
        var fileTools = toolbar.querySelector(".trix-button-group--file-tools");
        if (fileTools) {
            fileTools.style.display = "none";
        }
    }
});

})();

0 likes
1 reply
Tray2's avatar

I'm confused as what it is you want to do, and what your code is supposed to to, and what it actually does.

However, upload ing a file with ajax would look somethonh like this.

async function storeRecord() {

        let formData = new FormData();

        formData.append('_token', '{{ csrf_token() }}');
        formData.append('artist_name', getElement('#artist_name').value);
        formData.append('title', getElement('#title').value);
        formData.append('released', getElement('#released').value);
        formData.append('genre_id', getElement('#genre').value);
        formData.append('format_id', getElement('#format').value);
        formData.append('cover_image', getElement('#cover_image').files[0])

        fetch(`/records`, {
            method: 'POST',
            body: formData
        }).then(response => response.json()).then(response => {
            if (response.message === 'Success') {
                window.location.assign(`/`);
            }
        });
    }

If you have a upload that allows for more than one file to be selected, you need to append them one by one.

The getElement is just a helper function to make document.querySelector shorter to type.

    function getElement(selector) {
        return document.querySelector(selector);
    }

And then store it to the filesystem and the database.

    public function store(RecordRequest $request): Response
    {
        $path = '';
        $valid = $request->validated();
        
        if ($request->has('cover_image')) {
            $file = $request->file('cover_image');
            $path = $file->store('cover_images', 'public');
        }

        $record = Record::create(array_merge($valid, [
            'cover_image' => $path,
        ]));

      return response('{"message": "Success"}', 200);
    }

And of course if you have more than one image you need to look over them.

1 like

Please or to participate in this conversation.