Controllers in CI4
6 min read Quiz at the end
Write CI4 controllers that validate input, call models, and return views or JSON responses.
Controllers in CI4
namespace AppControllers;
use CodeIgniterHTTPResponseInterface;
class PostController extends BaseController {
public function index() {
$model = model(PostModel::class);
$data = ["posts" => $model->findAll()];
return view("posts/index", $data);
}
public function show(int $id) {
$post = model(PostModel::class)->find($id);
if (!$post) {
return $this->response->setStatusCode(404)
->setJSON(["error" => "Not found"]);
}
return view("posts/show", ["post" => $post]);
}
public function store() {
$rules = [
"title" => "required|max_length[255]",
"body" => "required",
];
if (!$this->validate($rules)) {
return redirect()->back()->withInput()->with("errors", $this->validator->getErrors());
}
model(PostModel::class)->insert($this->request->getPost());
return redirect()->to("/posts")->with("success", "Created!");
}
}
Topic Quiz · 4 questions
Test your understanding before moving on
1. What class do CI4 controllers extend?
💡 CI4 controllers extend AppControllersBaseController.
2. How do you return a view in CI4?
💡 return view("template", $data) renders a view and returns the response.
3. Which method returns JSON in CI4?
💡 $this->response->setJSON($data) returns JSON with correct Content-Type.
4. How do you get a POST value?
💡 $this->request->getPost("key") safely retrieves POST data in CI4.