How To Work with Filters in CodeIgniter 4 Tutorial

Share this Article
Reading Time: 7 minutes
19,646 Views

Filters are like middlewares in CodeIgniter 4, which is used to validate a request before processing. Controller 4 Filters allow us to perform actions either before or after the controllers execution. Unlike events, we can choose the specific URLs in which the filters will be applied to.

Inside this article we will see the concept of Filters in CodeIgniter 4. Using CodeIgniter filters we can validate our request. If we are creating an application in which authentication must be checked, CodeIgniter 4 filters will be right choice to do this.

Learn More –

Let’s get started.


CodeIgniter 4 Installation

To create a CodeIgniter 4 setup run this given command into your shell or terminal. Please make sure composer should be installed.

$ composer create-project codeigniter4/appstarter codeigniter-4

Assuming you have successfully installed application into your local system.


Environment (.env) Setup

When we install CodeIgniter 4, we will have env file at root. To use the environment variables means using variables at global scope we need to do env to .env

Either we can do via renaming file as simple as that. Also we can do by terminal command.

Open project in terminal

$ cp env .env

Above command will create a copy of env file to .env file. Now we are ready to use environment variables.

Enable Development Mode

CodeIgniter starts up in production mode by default. You need to make it in development mode to see any error if you are working with application.

Open .env file from root.

# CI_ENVIRONMENT = production

 // Do it to 
 
CI_ENVIRONMENT = development

Now application is in development mode.


What are Filters?

Filters are simple classes that implement CodeIgniter\Filters\FilterInterface.

They contain two methods: before() and after() which hold the code that will run before and after the controller respectively. Filter class must contain both methods but may leave the methods empty if they are not needed.

We can do any checks at before method which executes prior to any method of any controller.

A skeleton filter class looks like:

<?php

namespace App\Filters;

use CodeIgniter\Filters\FilterInterface;
use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;

class MyFilter implements FilterInterface
{
    public function before(RequestInterface $request, $arguments = null)
    {
        // Do something here
    }

    public function after(RequestInterface $request, ResponseInterface $response, $arguments = null)
    {
        // Do something here
    }
}

Create Filter

Open project into terminal and run this spark command to create filters.

$ php spark make:filter Auth --suffix

It will create a file with name AuthFilter.php inside /app/Filters folder.

Open AuthFilter.php,

<?php

namespace App\Filters;

use CodeIgniter\Filters\FilterInterface;
use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;

class AuthFilter implements FilterInterface
{
    /**
     * Do whatever processing this filter needs to do.
     * By default it should not return anything during
     * normal execution. However, when an abnormal state
     * is found, it should return an instance of
     * CodeIgniter\HTTP\Response. If it does, script
     * execution will end and that Response will be
     * sent back to the client, allowing for error pages,
     * redirects, etc.
     *
     * @param RequestInterface $request
     * @param array|null       $arguments
     *
     * @return mixed
     */
    public function before(RequestInterface $request, $arguments = null)
    {
        //
    }

    /**
     * Allows After filters to inspect and modify the response
     * object as needed. This method does not allow any way
     * to stop execution of other after filters, short of
     * throwing an Exception or Error.
     *
     * @param RequestInterface  $request
     * @param ResponseInterface $response
     * @param array|null        $arguments
     *
     * @return mixed
     */
    public function after(RequestInterface $request, ResponseInterface $response, $arguments = null)
    {
        //
    }
}

This is the initial code you will find inside your created filter.


Before Method in Filter

Inside any filter, by the help of before() method, We can return the $request object and it will replace the current Request, allowing you to make changes that will still be present when the controller executes. before filters are executed prior to your controller being executed.

We can implement our logic for prior execution inside this.


After Method in Filter

After filters are nearly identical to before filters, except that you can only return the $response object, and we cannot stop script execution.

This does allow us to modify the final output, or simply do something with the final output.


Register Filter

To use created filters inside application, we need to register it first.

Open Filters.php file from /app/Config folder.

  • Import filter class
  • Add into aliases array
# Import class

use App\Filters\AuthFilter;

# Update $aliases array

public $aliases = [
      
     //...

     "myauth" => AuthFilter::class
 ];

Now, we can use AuthFilter inside application with alias name myauth.


Example: Usage of Filters in Application

We are taking an example of authentication system. Inside this we have like a Login page from where user logs into application by putting email and password.

Task

We need to restrict Unauthorize access over application URLs.

Implementation

Suppose we are setting sessions somewhere in which we are storing a flag like isLoggedIn

Storing a User logged in status –

$session = session();

$session->set("isLoggedIn", 1);

More about sessions of CodeIgniter 4, Click here.

Checking a User login status in Filter

Open AuthFilter.php and add this login into before() method.

//...

public function before(RequestInterface $request, $arguments = null)
{
  if (!session()->get('isLoggedIn')) {
    return redirect()->to(base_url('login'));
  }
}

//...

Inside before() method, we are checking the status of session value. If it is not set, then it will redirect to login URL. User must be logged in.

Adding Filter to Route

Open Routes.php from /app/Config folder.

//...

$routes->get("login", "AdminController::login");

// Filter on single route
$routes->get("admin/profile", "AdminController::profile", ["filter" => "myauth"]);

// Filter on route group
$routes->group("admin", ["filter" => "myauth"] , function($routes){

    $routes->post("sales", "AdminController::sales");
    $routes->put("transactions", "ApiController::transactions");
});

//...

In the above code routes as /admin/profile, /admin/sales, /admin/transactions are protected routes. If we want to access then we must logged in.

We hope this article helped you to learn How To Work with Filters in CodeIgniter 4 Tutorial in a very detailed way.

Buy Me a Coffee

Online Web Tutor invites you to try Skillshike! Learn CakePHP, Laravel, CodeIgniter, Node Js, MySQL, Authentication, RESTful Web Services, etc into a depth level. Master the Coding Skills to Become an Expert in PHP Web Development. So, Search your favourite course and enroll now.

If you liked this article, then please subscribe to our YouTube Channel for PHP & it’s framework, WordPress, Node Js video tutorials. You can also find us on Twitter and Facebook.

Was this post helpful?

PHP Web Development Courses on Offer in just $4
PHP Web Development Courses on Offer in just $4