Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CodeIgniter dynamic URI routing possible?

My application is designed to provide a single profile page for each user, with the 3rd segment being the user's ID.

example.com/profile/page/1

Assuming user 1 is "Jon Jovi", using CI's routing I would like to generate this URI

example.com/jon_jovi

Is it possible to send this user's ID to config/routes.php, run a function to extract user 1's info from database and insert it like

$route['profile/page/$row->id'] = $row->first_name . '_' . $row->last_name;

Any thought or suggestions on how to do this are much appreciated - thanks.

like image 591
pepe Avatar asked Dec 11 '25 09:12

pepe


1 Answers

Not sure this needs to be in your config/routes.php at all: why don't you just create a controller that takes the name and does the lookup?

EDIT: I take it back. This is actually kinda painful to do, particularly because you want it to live on the root of the domain (i.e. it would be easy to to do example.com/p/{username}, but example.com/{username} is messy).

Easiest way to do this is to use CodeIgniter 2.0+'s ability to override the 404 handler and the _remap function. First, do this in the config/routes.php file:

$route['404_override'] = 'notfound';

Then create the controller:

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class NotFound extends CI_Controller
{
  function __construct()
  {
    parent::__construct();
  }

  public function _remap($method)
  {
    if($this->uri->total_segments() == 1){
      // try it out
      $this->profile();
    }else{
      show_404($this->uri->uri_string());
    }
  }

  function profile()
  {
    echo "Showing profile for [" . $this->uri->segment(1) . "]";
  }
}

You have to implement a view for the 404 page as this overrides it, but any requests that don't map to an existing controller come in here and you can dispatch them however you want, including translating the name into a db ID.

Let me know if that works for you.

like image 143
Femi Avatar answered Dec 12 '25 23:12

Femi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!