Delete records in CodeIgniter 4

The next CRUD operation that we are going to see would be the one that allows us to delete a record from our database; We can implement some modal function to this, how to get started in our course Course to take the first steps in CodeIgniter 4: the php framework of the future, but in this entry we are going to see a very simple example that would be to delete the record directly without a modal; for that, we are going to define the following function inside our controller that we created earlier:

    public function delete($id = NULL)
    {
 
        $movie = new MovieModel();
 
        if ($movie->find($id) == NULL) {
            throw PageNotFoundException::forPageNotFound();
        }
 
        $movie->delete($id);
 
        return redirect()->to('/movie')->with('message', 'Película eliminada con éxito.');
    }

It is a very simple function, the important thing here is referential the elements that we want to eliminate, for that we do some previous validations to know if the record exists, and if it does not exist, return a 404 page to finally send to some other page, for example , the list, and for that we make a redirection to the corresponding view.

Then, to call it, we can create a link:

<a class="btn btn-danger btn-sm float-right" href="<?= route_to('store_movie_show', $m->id) ?>"><i class="fa fa-eye"></i> Ver</a>

- Andrés Cruz

En español

Andrés Cruz

Develop with Laravel, Django, Flask, CodeIgniter, HTML5, CSS3, MySQL, JavaScript, Vue, Android, iOS, Flutter

Andrés Cruz In Udemy

I agree to receive announcements of interest about this Blog.

!Courses from!

10$

On Udemy

There are 2d 19:01!


Udemy

!Courses from!

4$

In Academy

View courses

!Books from!

1$

See the books
¡Become an affiliate on Gumroad!