Inside a controller, $this->request is the incoming request and $this->response is what you send back.
Reading input
$this->request->getPost('name')— a form field$this->request->getPost(['name', 'email'])— several fields as an array$this->request->getGet('page')— query string (?page=2)$this->request->getVar('q')— from GET or POST$this->request->getJSON(true)— JSON body as an array$this->request->getFile('photo')— an uploaded file$this->request->getMethod(),getIPAddress(),isAJAX()
Input is returned raw. Validate it, and escape it with esc() when you print it.
Kinds of responses
return view('home', $data);return redirect()->to('posts');,redirect()->back(),redirect()->route('posts')return $this->response->setJSON($data);return $this->response->setStatusCode(201)->setJSON($data);return $this->response->download($path, null);
404 page
throw \CodeIgniter\Exceptions\PageNotFoundException::forPageNotFound();
Example
Example — Contact form handler with JSON for AJAX
PHP
<?php
public function send()
{
$data = $this->request->getPost(['name', 'email', 'message']);
if (! $this->validateData($data, [
'name' => 'required|max_length[100]',
'email' => 'required|valid_email',
'message' => 'required|min_length[10]',
])) {
if ($this->request->isAJAX()) {
return $this->response->setStatusCode(422)->setJSON(['errors' => $this->validator->getErrors()]);
}
return redirect()->back()->withInput();
}
model('ContactModel')->insert($data);
return $this->request->isAJAX()
? $this->response->setJSON(['ok' => true])
: redirect()->to('contact')->with('success', 'Thank you! We will reply soon.');
}
A normal form post redirects with a success message. An AJAX post gets {"ok":true}, or status 422 with {"errors":{...}} when validation fails.