How To Work with Filters in CodeIgniter 4 Tutorial

Share this Article
Reading Time: 6 minutes
442 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 –

Note*: For this article, CodeIgniter v4.1 setup has been installed. May be when you are seeing, version will be updated. CodeIgniter 4.x still is in development mode.

Let’s get started.


Download & Install CodeIgniter 4 Setup

We need to download & install CodeIgniter 4 application setup to system. To set application we have multiple options to proceed.

Here are the following ways to download and install CodeIgniter 4 –

  • Manual Download
  • Composer Installation
  • Clone Github repository of CodeIgniter 4

Complete introduction of CodeIgniter 4 basics – Click here to go. After going through this article you can easily download & install setup.

Here is the command to install via composer –

$ composer create-project codeigniter4/appstarter codeigniter-4

Assuming you have successfully installed application into your local system.


Turn Development Mode On

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

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.

CodeIgniter starts up in production mode by default. Let’s do it in development mode. So that while working if we get any error then error will show up.

# CI_ENVIRONMENT = production

// Do it to 

CI_ENVIRONMENT = development

Now application is in development mode.


What are Filters in CodeIgniter 4?

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\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;
use CodeIgniter\Filters\FilterInterface;

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
{
	public function before(RequestInterface $request, $arguments = null)
	{
		//
	}

	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 in Application

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

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.

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.

Find More on CodeIgniter 4 here

Leave a Comment