UPLOAD IMAGE WITH LARAVEL

Mar 22, 2024 Copy Link

I was suffering from a problem in sending an image within newsletters because when I drag it into CKEditor it is converted into base64 format and presented broken so, I thought to create a new separate section for uploading the attachments that will be used in the newsletters or whatever section hence, I worked on that feature without satisfaction since it kinda wasting my time, considering that section will contain only one input file. So, I searched for a long time about pretty thing to carry out the task and I found that I could make a bit of change to the configuration that allows uploading the dragged image on the server so, lemme show you how we can accomplish that

 

First of all, we will register a new route in the `web.php` file:

 

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\Dashboard\CKEditorController;

Route::post('ckeditor/upload-attachment', CKEditorController::class)
    ->name('ckeditor.uploadAttachment');

 

In addition, we will create an Invokable Controller and then type the following code:

 

/**
 * Handle the incoming request.
 *
 * @param  \Illuminate\Http\Request  $request
 * @return \Illuminate\Http\JsonResponse
 *
 * @throws \Symfony\Component\HttpFoundation\File\Exception\FileException
 */
public function __invoke(Request $request)
{
    // The `upload` key is fixed whatever the textarea name
    if ($request->hasFile('upload')) {
        $fileName   = $request->file('upload')->getClientOriginalName();
        $extension  = $request->file('upload')->getClientOriginalExtension();
        $hashedName = md5($fileName) . '.' . $extension;
        $path       = storage_path("app/public/tmp");

        $request->file('upload')->move($path, $hashedName);

        return response()->json([
            'uploaded' => true,
            'fileName' => $fileName,
            'url'      => asset("storage/tmp/{$hashedName}")
        ]);
    }
}

 

Finally, update the editor configuration in the blade view:

 

let editor = CKEDITOR.replace("your-textarea-id");

editor.config.filebrowserUploadUrl = 
"{{ route('admin.ckeditor.uploadAttachment', ['_token' => csrf_token()]) }}";
editor.config.filebrowserUploadMethod = "form";

 

When we try to upload an image again into the editor we will get a successful toast indicating that the image was uploaded on the server 🧙‍♂️

 

Share via

Filed in:

Tips CKEditor
Mahmoud Ramadan

Mahmoud Ramadan

Mahmoud is the creator of Digging Code and a contributor to Laravel since 2020.

Most recent

  • Get your environment ready to welcome Laravel v12

    Get your environment ready to we...

    FREE

  • How to generate Arabic PDF using TCPDF

    How to generate Arabic PDF using...

    FREE

  • What is SQL Injection

    What is SQL Injection

    FREE