semicolon24's avatar

ERROR CRUD laravel with upload image

I have a data input form with input functions for title, slug, category, image for (thumbnail), and body for (description),

In the body I use a textarea that is integrated with Summernote. then how do I want to add code to my controller so that on the body part I can upload images please enlighten me, thank you..

public function store(Request $request) {

    $request->validate([
        'title' => 'required',
        'slug' => 'required|unique:posts',
        'category_id' => 'required',
        'image' => 'image|file|mimes:jpg,png',
        'body' => 'required'
    ]);

    $int = $request->all();

    
    if ($request->hasFile('image')) 
    { 
        $image = $request->file('image'); 
        $imageName = date('d-m-Y') . '.' . $image->getClientOriginalName(); 
        $path = public_path('/uploads/post'); 
        $image->move($path, $imageName); 
        $int['image'] = $imageName; 
    }

    $int['user_id'] = auth()->user()->id;
    $int['excerpt'] = Str::limit(strip_tags($request->body));
    $int['body'] = (strip_tags($request->body));

    Post::create($int);

    return redirect('/mypost')->with('success', 'Post success save!!');
}
0 likes
1 reply
gych's avatar

You can use DomDocument to handle the added images.

Here is an example, but I could not test it myself.

    $dom = new \DomDocument();
    $dom->loadHtml($request->body, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);

    $images = $dom->getElementsByTagName('img');
    foreach ($images as $key => $img) {
        $data = $img->getAttribute('src');

        if (preg_match('/data:image\/(png|jpg|jpeg);base64/', $data)) {
            preg_match('/data:image\/(png|jpg|jpeg);base64,(.*)/', $data, $matches);
            $imageData = base64_decode($matches[2]);

            $imageName = 'image_' . time() . '_' . $key . '.png';

            file_put_contents(public_path('/uploads/post/') . $imageName, $imageData);

            $img->removeAttribute('src');
            $img->setAttribute('src', '/uploads/post/' . $imageName);
        }
    }

    $int['body'] = $dom->saveHTML();

You can also use the summernote callbacks for this but then you'll have to handle the upload via API call and add that to your request: https://summernote.org/deep-dive/#onimageupload

But by using this you will need a different approach in your store method to check if the uploaded image is still present in the body before storing the post.

Please or to participate in this conversation.