CRUD — Create, Read, Update, Delete — is the base of every admin panel. Here is the full flow for posts.
Routes
GET posts→ listGET posts/new→ create formPOST posts→ save newGET posts/(:num)/edit→ edit formPOST posts/(:num)/update→ save changesPOST posts/(:num)/delete→ delete
Using POST for update and delete keeps them out of reach of simple links and lets CSRF protection check them. (You can also use $routes->resource() or presenter() for ready-made routes.)
Controller flow
- Validate input with
$this->validate($rules) - On failure:
redirect()->back()->withInput()(errors are kept) - On success: save with the model, then redirect with a flash message:
->with('success', 'Saved')
Not found
If find($id) returns null, throw PageNotFoundException::forPageNotFound() to show a 404 page.
In the views
<?= csrf_field() ?>in every formold('title', $post['title'] ?? '')to refill fieldssession('success')to show the message
Example
<?php
namespace App\Controllers;
use App\Models\PostModel;
use CodeIgniter\Exceptions\PageNotFoundException;
class Posts extends BaseController
{
private array $rules = ['title' => 'required|max_length[255]', 'body' => 'required'];
public function create()
{
if (! $this->validate($this->rules)) {
return redirect()->back()->withInput();
}
model(PostModel::class)->insert($this->request->getPost(['title', 'body']));
return redirect()->to('posts')->with('success', 'Post created');
}
public function update(int $id)
{
$model = model(PostModel::class);
$model->find($id) ?? throw PageNotFoundException::forPageNotFound();
if (! $this->validate($this->rules)) {
return redirect()->back()->withInput();
}
$model->update($id, $this->request->getPost(['title', 'body']));
return redirect()->to('posts')->with('success', 'Post updated');
}
public function delete(int $id)
{
model(PostModel::class)->delete($id);
return redirect()->to('posts')->with('success', 'Post deleted');
}
}
// Routes.php
// $routes->get('posts', 'Posts::index');
// $routes->post('posts', 'Posts::create');
// $routes->post('posts/(:num)/update', 'Posts::update/$1');
// $routes->post('posts/(:num)/delete', 'Posts::delete/$1');
Invalid input sends the user back to the form with the errors and old values. A valid save redirects to /posts with a one-time success message. Updating an id that does not exist shows a 404 page.