Home > OS >  How to Implement Dynamic Routing from Database in CodeIgniter 4
How to Implement Dynamic Routing from Database in CodeIgniter 4

Time:02-06

As I have mentioned, may you please help me to implement dynamic routing from the database in CodeIgniter 4 ? I have implemented a blog where all blog posts store in the posts table. The table has the slug column which is used to fetch a blog.

Site pages will be look like:

www.mysite.com/how-to-work-with-ci

www.mysite.com/your-health-your-wealth

As, we have already implemented such features in Codeigniter 3, but I did not found anything equivalent in CI4.

Please help me regarding this. Please let me know if you want any other info regarding this from me, thanks...

CodePudding user response:

It's actually quite easy. First, you will need to configure the routes as follow in routes files :

$routes->get('blogs/(:any)', 'BlogController::show/$1');

Here (:any) is a placeholder (slug) for the dynamic route which will be passed to your controller.

In your BlogController, you will need to fetch the value passed to this parameter.

show($slug){
... switch($slug)
}

You can also refer to the following for better of the routes in CI4.

https://codeigniter.com/user_guide/incoming/routing.html

CodePudding user response:

Try this:

// app\Config\Routes.php

$routes->get('/', 'Home::index');
$routes->addPlaceholder('admin', 'admin');
$routes->addPlaceholder('pub', '[a-z] ');

$routes->get('(:admin)', 'Home::$1');
$routes->get('(:admin)/(:any)', 'Home::$1/$2'); // remember $1 = admin

$routes->get('(:pub)', 'Home::index/$1'); // you can use (:any)
// app\Controllers\Home.php

<?php

namespace App\Controllers;

class Home extends BaseController
{
    public function index($slug = 'home')
    {
        echo 'INDEX: ' . $slug;
    }

    public function admin($page = 'main admin')
    {
        echo 'ADMIN: ' . $page;
    }
}

  •  Tags:  
  • Related