Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Contents

Requests and responses

A request is what the browser sent to the site: the address, parameters, form fields. A response is what the site sends back. In a controller the request is available as $this->request and the response as $this->response. There is no need to create them: both objects come from BaseController.

Address parameters

Parameters after the question mark are read with getGet():

// app/Controllers/Posts.php
public function search(): string
{
    $query = $this->request->getGet('q');
 
    return 'You searched for: ' . esc($query);
}

Add the route $routes->get('search', 'Posts::search'); and open /search?q=php — the page shows "You searched for: php". If the parameter is missing, getGet() returns null. The esc() function makes text safe to output; the lesson about views covers it.

Form fields

Data sent by a form with the POST method is read with getPost():

public function create(): string
{
    $title = $this->request->getPost('title');
 
    return 'Title received: ' . esc($title);
}

Without an argument getPost() returns an array of all fields.

Other request methods

MethodWhat it returns
getGet('q')An address parameter
getPost('title')A form field
getJSON(true)The JSON request body as an array
getMethod()The request method: GET, POST
is('post')true if the request was sent with POST
getIPAddress()The visitor's address

Redirect

After a form is saved the visitor is sent to another page:

public function create()
{
    // the data is saved here
 
    return redirect()->to('/posts');
}

The browser opens /posts by itself. There are other variants too:

return redirect()->route('posts.show', [5]); // by route name
return redirect()->back();                   // to the previous page

A JSON response

JSON is a text data format understood by JavaScript programs and mobile apps:

public function status()
{
    return $this->response->setJSON(['status' => 'ok', 'posts' => 12]);
}

The browser receives a string like {"status":"ok","posts":12} and a header with the application/json type.

Status code

The status code tells how the request ended: 200 is success, 404 is not found. setStatusCode() sets it:

return $this->response->setStatusCode(404)->setBody('Post not found');

Common mistake

Calling redirect()->to('/posts'); without the word return does nothing: the function only creates a response object, and the framework sends it after receiving it from the method. The method keeps running and the visitor stays on a blank page. Always write return before redirect().

Thanks for reading!

Donate to the site — we work hard for you.