CodeIgniter 4 How to Work with Redirection Tutorial

Reading Time: 5 minutes
22,858 Views

Effective redirection is a key component of web development, allowing you to effortlessly navigate users through your application’s many pages and functions.

Mastering the art of redirection in CodeIgniter 4 is critical for improving user experience, handling authentication, and guaranteeing fast request routing.

Read More: Step by Step How To Setup Cron Jobs in CodeIgniter 4 Tutorial

We will walk you through the process of working with redirection in CodeIgniter 4 in this tutorial. We will investigate the many ways and approaches available inside the framework for redirecting users to various pages, URLs, and actions.

Here, we have few cases mentioned as –

  • Redirection from one route to another route
  • Route Redirection with data
  • Named route Redirection.
  • Redirection with Flash Message, Inputs
  • Redirection Permanent 301

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 is Redirection?

The process of transferring a user from one URL to another is referred to as redirection in web development. CodeIgniter, a prominent PHP framework, includes capabilities and functions for successfully managing redirection.

Redirection is frequently used to manage problems like URL changes, page not found errors, login/authentication, and website navigation optimisation. CodeIgniter provides multiple methods for achieving various types of redirection.

Understanding Redirection with Examples

Open Routes.php from /app/Config folder. Add these sample routes into it.

//...

# CASE #1
$routes->get("list-user", "User::listUser");
$routes->match(["get", "post"], "add-user", "User::addUser");

# CASE #2
$routes->get("list-user", "User::listUser", ["as" => "users"]); // Named route

Here, we have two routes.

  • /list-user to list users whereas
  • /add-user is for both get and post request type.

It will be used for both rendering a layout and submitting form data.

Read More: About Database Forge Class of CodeIgniter 4 Tutorial

Now, we want that when we submit form data to /add-user route via POST we need redirect after success to /list-user route.

Method #1: Basic Redirection

//...

public function addUser()
{
  if ($this->request->getMethod() == "post") {

    // Save data here

    return redirect()->to(site_url("list-user"));
  }
}

//...

Method #2: Redirect With Named Route

To use named route, we have an option to use route().

//...

public function addUser()
{
  if ($this->request->getMethod() == "post") {

    // Save data here

    return redirect()->route("users"); // Calling name defined in 'as' in Routes.php
  }
}

//...

Method #3: Redirect To Previous URL

Need to go to back of the route from where we came, Here we have –

//...

// Go back to the previous page
return redirect()->back();

//...

Method #4: Redirection with Flash Message

If we want to go to location with some session flash value, So here we have the case.

//...

public function addUser()
{
  if ($this->request->getMethod() == "post") {

    // Save data here

    return redirect()->route("users")->with("success", "Successfully, we are sending");
  }

  return view("add-user");
}

// Destination method of redirected URL
public function listUser()
{
    echo session()->get("name");
}

//...

Method #5: Redirection With Form Inputs

In Form submits, when we have errors then we loose old value from form inputs. So here, inside this case we are going to redirect with inputs.

//...

<form method="post" action="<?= site_url('add-user') ?>">

  <p>
      Name: <input type="text" name="name" value="<?= old('name') ?>">
  </p>
  <p>
      Email: <input type="text" name="email" value="<?= old('email') ?>">
  </p>

  <button>Submit</button>

</form>
               
//...

public function addUser()
{
   if ($this->request->getMethod() == "post") {

      // Save data here

       return redirect()->to("add-user")->withInput();
   }

   return view("add-user");
} 

//..

Read More: https://onlinewebtutorblog.com/methods-to-create-database-in-codeigniter-4/

Method #6: Redirect Permanent

Route redirection from Routes.php file, we are going to redirect URLs automatically to a different URL like 301 redirection.

//...

$routes->addRedirect('From Route', 'To Route');

//...

That’s it.

We hope this article helped you to learn about CodeIgniter 4 How To Work with Redirection 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.