Welcome Guest, Not a member yet? Register   Sign In
Question about making sure an image is completely removed from your CRUD application
#1

Question about making sure a image is completely removed from the database and file path when using CRUD 

I'm currently building an application using CRUD. The app displays images. I followed a tutorial about their method on how to building a CRUD app with images. My current bug is when I delete the image, it is removed from the database however it's not removed from the uploads folder. Additional information, before submitting the form the image you select will be stored in the database and in the folder you create located the public directory. What else can I add to my program that would accomplish complete deletion from the database and file path. Thanks!

I have snippets of my program posted here:

My Controller:
PHP Code:
<?php

namespace App\Controllers;

use 
App\Models\Products;

/**
 * Product Class | learn how to load images into table
 */
class Product extends BaseController
{
    /**
    * Index Method | main display page
    */
    public function index()
    {
        $model = new Products();

        $data = [
            'title' => 'Product | how to load images',
            'product' => $model->findAll(),
        ];

        return view('products/index'$data);
    }

    /**
    * Create Method | create a product
    */
    public function create()
    {
        $data = [
            'title' => 'Create Product'
        ];

        if ($this->request->getMethod() === 'post') {

            $ruels = [
                'name'        => 'required',
                'description' => 'required',
                'price'      => 'required',
            ];

            if (! $this->validate($ruels)) {

                $data['validation'] = $this->validator;

            } else {

                $model = new Products();
                $file $this->request->getFile('image');

                if ($file->isValid() && ! $file->hasMoved()) {

                    $image $file->getRandomName();
                    $file->move('assets/uploads/'$image);

                }

                $model->save([
                    'name'        => $this->request->getPost('name'),
                    'description' => $this->request->getPost('description'),
                    'price'      => $this->request->getPost('price'),
                    'image'      => $image,
                ]);
    
                
return redirect()->to(base_url('products'))->with('status''Product Added Successfully');

            };

        }

        return view('products/create'$data);
    }

    /**
    * Edit Method | edit or update the table
    */
    public function edit(mixed $id null)
    {
        $model = new Products();

        $data = [
            'title' => 'Edit Products',
            'item' => $model->find($id),
        ];

        if ($this->request->getMethod() === 'put') {

            $item        $model->find($id);
            $currentImage $item['image'];
            $file        $this->request->getFile('image');
            
            
if ($file->isValid() && ! $file->hasMoved()) {
                
                
if (file_exists("assets/uploads/{$currentImage}")) {
                    unlink("assets/uploads/{$currentImage}");
                }
    
                $image 
$file->getRandomName();
                $file->move('assets/uploads/'$image);
    
            
} else {
    
                $image 
$currentImage;
    
            
};

            $model->update($id, [
                'name'        => $this->request->getPost('name'),
                'description' => $this->request->getPost('description'),
                'price'      => $this->request->getPost('price'),
                'image'      => $image,
            ]);

            return redirect()->to(base_url('products'))->with('status''Product Updated Successfully');

        };

        return view('products/edit'$data);
    }

    /**
    * Delete Method | remove data from the table
    */
    public function delete(mixed $id null)
    {
        
        
if ($this->request->getMethod() === 'delete') {
            
            $model 
= new Products();

            $model->delete($id);

            return redirect()->to(base_url('products'))->with('status''product was deleted');

        }
    }


My View:
PHP Code:
<?= $this->extend('App\Views\templates\default'); ?>

<?= $this->section('content'); ?>
    <main id="main" role="main">
        <h1>Create Product Home Page</h1>
        <?php
            
if (session()->getFlashdata('error')) {
                echo '<h4>'.session()->getFlashdata('error').'</h4>';
            };
        ?>
        <div>
            <a href="<?= base_url('products'); ?>">return</a>
        </div>
        <div>
            <form action="<?= base_url('products/create'); ?>" method="post" enctype="multipart/form-data">

                <?= csrf_field() ?>

                <label for="name">Product Name</label><br>
                <input type="text" name="name" id="name"><br>

                <label for="description">Description</label><br>
                <input type="text" name="description" id="description"><br>

                <label for="price">Price</label><br>
                <input type="text" name="price" id="price"><br>

                <label for="image">Image</label><br>
                <input type="file" name="image" id="image"><br>

                <?php if(isset($validation)): ?>
                    <div>
                        <?= $validation->listErrors(); ?>
                    </div>
                <?php endif; ?>

                <input type="submit" name="submit" value="Create Product">
            </form>
        </div>
    </main>
<?= $this->endSection(); ?>
  
My file path:
Code:
public:
    assets:
        uploads:
Reply
#2

@Son of Troy,  What version of CI are you using?
Reply
#3

Your delete() method just delete the record in the database.
You need to add the code to delete the file in the uploads folder.
Reply
#4

(This post was last modified: 07-15-2022, 10:45 PM by demyr.)

It is not so difficult to delete from the folder as well. You need "unlink" function in PHP and you can find regular php tutorials on internet for this. Let me write you the basic idea:

Here is an example of Controller part. In your view, I assume you have a form tag containing the inputs I write down here

   
PHP Code:
$product_id $this->request->getVar('product_id'); // Probably you will keep it as a hidden input in your form
$product_image_link $this->request->getVar('product_image_link'); //the name part of the image link. Keep it as a hidden input in your form so that you can use it here.
$product_image_id $this->request->getVar('product_image_id'); // you will need this to delete from the database

    $folder 'uploads/products/product-'.$product_id.'/images';
        if(file_exists($folder.'/'.$product_image_link)) {
            unlink($folder.'/'.$product_image_link);
           $this->YourProductModel->delete($product_image_id); //deleting from the database
        

Good luck

P.S. If you cannot display directly the name of the image for $product_image_link , you can display the complete url that you keep in your database and use explode() function here in order to get the name part of it.
Reply
#5

(07-15-2022, 04:49 PM)php_rocs Wrote: @Son of Troy,  What version of CI are you using?

@php_rocs I'm currently using CodeIgniter V.4
Reply
#6

@demyr  Thank you for your help. I used your solution and made small changes. and now it's working. I'll post the solution below.

The delete method used to remove data from the men's / boy's wrestling roster. The data is removed from both the database and filesystem. 
PHP Code:
    /**
    * DeleteRosterBoys Method | Remove data from rosterBoys
    */
    public function deleteRosterBoys(mixed $id null)
    {
        if ($this->request->getMethod() === 'delete') {

            $rosterboys = new RosterBoys();

            $findImage $rosterboys->find($id);
            $getImage $findImage['image'];
            
            
if (file_exists("assets/uploads/$getImage")) {

                unlink("assets/uploads/$getImage");

            };

            $rosterboys->delete($id);

            return redirect()->to(base_url('controlpanel'))->with('status''Men\'s roster Deleted sucessfully');
        };
    
Reply




Theme © iAndrew 2016 - Forum software by © MyBB