'Codeigniter 4 while unlinking shows the error: Trying to access array offset on value of type null

Into my project in Codeigniter 4 I want to delete the record from database as well as I want to unlink the file present into that record but it gives me the error of

Trying to access array offset on value of type null

Till now I have tried this but its not working according to what do I want, below is my code



public function delete($id = null)
{

    $model = new AbcModel();
    

    try{
        $id=$this->request->getPost('id');
        $this->record = $model->where('id', $id)->first();
        $image = $this->record['image'];

        if(unlink('.'.$image)){
            $model->where('id', $id)->delete();
            echo "delete";

        }
        

        
    }
    catch(\Exception $e){
        echo $e->getMessage();
    }
}
}

My Model

<?php namespace App\Models;
 
class AbcModel extends MyModel
{

protected $table = 'abc';
protected $primaryKey = 'id';

}

Into the database I have saved the file as /public/uploads/abcfolder/Tulips.jpg



Solution 1:[1]

so it like me


<?php namespace Modules\Common\Libraries;

use CodeIgniter\HTTP\Response;

class  CustomFile
{
    protected string $error;

    public function __construct()
    {
        $this->error = '';
    }

    /**
     * @return string
     */
    public function getError(): string
    {
        return $this->error;
    }

    public function removeSingleFile( $path)
    {
        try {

            if (file_exists($path)) {
                unlink($path);
            }


        } catch (\Exception $e) {
            $this->error = $e->getMessage();

        }

    }


    


}

in your ctl or service

/**
     * edit function
     * @method : DELETE with params ID
     * @param $id
     * @param $foreignKey
     */
    public function delete($id)
    {


$cfs  = new  CustomFile();
$model = new MyModel();

            $deleteById = $model->where(['id' => $id])->findAll();
          
        

        if (is_null($deleteById)) $this->httpException(lang('Shared.api.exist'), ResponseInterface::HTTP_NOT_FOUND);


        $model->where(['id' => $id])->delete();

        foreach ($deleteById as $path) {

            $cfs->removeSingleFile(ROOTPATH . $path->path);
        }


    }

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 paliz