Hitesh
Hitesh

Reputation: 33

Routing slug or url from the database in Codeigniter

I have some controllers: Post, Pages, Authors. On each controller, I want to set the individual URL from the database. The structure of the database page: There will be thousands of records in the database.

enter image description here how can this be implemented, take also indicate every URL will load from the database on the basis of slug. I stuck in this from last two day

Current Url structure is -

http://127.0.0.1/hmvc/post/post_details?id=1

I want urls something like this

http://127.0.0.1/hmvc/blog-post-1

Upvotes: 0

Views: 2021

Answers (2)

Tanvir Ahmed
Tanvir Ahmed

Reputation: 483

Please check the following code by placing it at the bottom of your config/routes.php file.

What it does is, check if 'blog-post-' is present in the uri(not in querystring) part. If present, then explode it and check if the second part is a valid positive integer. If yes, then set the route rule for 'post/post_details/{NUMBER}' for the uri.

It will not break the routes rules for other controllers(Pages, Authors) by trying to redirect their hits to 'post' controller.

$uri = $_SERVER['REQUEST_URI'];
$check_part = 'blog-post-';

if (strpos($uri, $check_part) !== FALSE) {
    $uri_parts = explode('blog-post-', $uri);
    if (count($uri_parts) == 2) {
        $id = intval($uri_parts[1]);
        if ($id > 0) $route[ltrim($uri, '/')] = 'post/post_details/'.$id;
    }
}

Upvotes: 0

marcogmonteiro
marcogmonteiro

Reputation: 2162

Since you have the slugs already in your database I'm assuming that you already have the CRUD of that table done and you just want to interact with it.

First your controller and method:

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

class Post extends CI_Controller {

    public function post_details($slug)
    {
        $this->load->model('article_model', 'article');
        $this->data['article'] = $this->article->get_by_slug($slug);
    }

}

/* End of file post.php */
/* Location: ./application/controllers/post.php */

Then your model:

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

class Article_model extends CI_Model
{

    public function get_by_slug($slug = null)
    {
        if (is_null($slug)) {
            return array();
        }
        return $this->db->where('slug', $slug)
            ->get('posts')
            ->row();
    }

}

/* End of file article_model.php */
/* Location: ./application/models/article_model.php */

Finally your routes should look like this:

$route['default_controller'] = 'dashboard';
$route['404_override'] = '';
$route['translate_uri_dashes'] = false;
$route['(:any)'] = 'post/post_details/$1';

Upvotes: 1

Related Questions