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

Time:01-26

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

CodePudding user response:

I think you have problem with your delete query not with unlinking so you are getting the error of Trying to access array offset on value of type null. So I have rectified your codes try it once

$id=$this->request->getPost('id');
$model = new CurriculumModel();
$record = $model->find($id);
$image = $record['image'];

$file='.'.$image;
if(is_file($file))
{
    unlink($file);
    $model->delete($id);
    echo 'delete';
}

This code does works for me, I am not sure whether it will work for you or not but give it a try.

  •  Tags:  
  • Related