Codeigniter user profile URL - php

I have a controller called user which just loads the user profile page for now
class user extends CI_Controller {
public function __construct(){
parent::__construct();
}
public function index($username = null){
//load index page
$this->load->view('profile/index');
}
}
i have also routed it so i can load it from user/$username in routes
//user profiles pretty url
$route['user/(:any)'] = "user/index/$1";
the thing is i would like to change it and allow directly the users to go to their profiles without typing user/$username and instead $usernamd like mysite.com/$username...
I tried it but it messes up everything.how can i achieve this?
Thanks.

I guess the only way to achieve something like this is to add all other controllers to your routes file.
You could try something like this
$route['controller'] = "controller";
$route['controller/(:any)'] = "controller/$1";
$route['(:any)'] = "user/$1";
Combined with the _remap function as stated here. In your users controller.

Have you heard of the _remap function?
If you replace the index() function with this:
public function _remap($username = null) {
$this->load->view('profile/index');
}
It will probably work. You don't have to use the routes.php.

I used something like this for my users ; this "p" function in my users controller, mysite.com/users/p/$user_id , routes are good but I solved it like this, you could also do it do index function if you don't want something like "p"
function p()
{
$total_slashes = count ( $this->uri->segment_array () );
$last = end ( $this->uri->segments );
if ($total_slashes == 3) {
$data ['userdetails'] = $this->users_model->userDetails ( $last );
// $last is our user_id
$this->load->view('profile/index');
}
}

Related

Laravel routing white page with Controller

I'm using Laravel 8.
I'm trying to save ip addresses who visited the page. I can save it to the database. But there is a white page problem on page. How can i solve this problem? Thanks.
web.php
Route::get('/', [IpController::class,'addData'], function () {
$slides = App\Slide::all();
$themes = App\Theme::all();
return view('tema.kurumsal.index', compact('slides','themes'));
});
IpController.php
class IpController extends Controller
{
//
function addData(Request $req)
{
$ip = new Ip;
$ip->ip = $req->ip();
$ip->cihaz = $req->userAgent();
$ip->url = $req->getRequestUri();
$ip->save();
}
}
There is no 3rd parameter on Route::get, so what is that function doing ? This is the Source code.
You have a white page because you are not returning a view or data on your IpController.
Have another look at the documentation. There is no 3rd parameter.
Your code should be like this:
Route::get('/', [IpController::class,'addData']);
And your controller:
class IpController extends Controller
{
public function addData(Request $req)
{
$ip = new Ip;
$ip->ip = $req->ip();
$ip->cihaz = $req->userAgent();
$ip->url = $req->getRequestUri();
$ip->save();
$slides = \App\Slide::all();
$themes = \App\Theme::all();
return view('tema.kurumsal.index', compact('slides','themes'));
}
}

Pagination-URI in Codeigniter 4

I began writing a webapp in Codigniter 4 and currently, i'm stuck with the pagination.
I created a controller, a model an a view to retrieve database entries für usergroups and used CI's built-in pagination-library.
UsergroupsModel:
<?php namespace App\Models;
use CodeIgniter\Model;
class UsergroupsModel extends Model{
protected $table = 'roles';
protected $allowedFields = [];
protected $beforeInsert = ['beforeInsert'];
protected $beforeUpdate = ['beforeUpdate'];
public function getGroups(){
$db = \Config\Database::connect();
$builder = $db->table('roles');
$query = $builder->get();
$results = $query->getResultArray();
return $results;
}
}
Controller (Usergroups):
<?php namespace App\Controllers;
use App\Models\UsergroupsModel;
class Usergroups extends BaseController
{
public function index()
{
//Helper laden
helper(['form','template','userrights']);
$data = [];
$data['template'] = get_template();
$data['info'] = [
"active" => "menu_dash",
"title" => "Dashboard",
"icon" => "fab fa-fort-awesome fa-lg",
"sub" => "Frontend",
];
//Check Permissions
$data['userrights'] = get_userrights(session()->get('id'));
if($data['userrights'][1] == 1)
{
foreach($data['userrights'] as $key => $value){
$data['userrights'][$key] = '1';
}
}
else
{
$data['userrights'] = $data['userrights'];
}
$model = new UsergroupsModel;
$model->getGroups();
$pager = \Config\Services::pager();
$data['usergroups'] = $model->paginate(5);
$data['pager'] = $model->pager;
//Create Views
echo view($data['template'].'/templates/header', $data);
echo view($data['template'].'/backend/navigation');
echo view($data['template'].'/templates/sidebar');
echo view($data['template'].'/backend/usergroups');
echo view($data['template'].'/templates/footer');
}
//--------------------------------------------------------------------
}
In the view, i got my pagination by using
<?= $pager->links() ?>
The default pagination works fine, but i get an URI like https://DOMAIN.DE/usergroups?page=2
In the official Codeigniter 4 docs for the pagination, you can find the following:
Specifying the URI Segment for Page
It is also possible to use a URI segment for the page number, instead of the page query parameter. >Simply specify the segment number to use as the fourth argument. URIs generated by the pager would then >look like https://domain.tld/model/[pageNumber] instead of https://domain.tld/model?page=[pageNumber].:
::
$users = $userModel->paginate(10, ‘group1’, null, 3);
Please note: $segment value cannot be greater than the number of URI segments plus 1.
So in my controller i changed
$data['usergroups'] = $model->paginate(5);
to
$data['usergroups'] = $model->paginate(5,'test',0,2);
and in the view i added 'test' as a parameter.
<?= $pager->links('test') ?>
In the Routes i added
$routes->get('usergroups/(:num)', 'Usergroups::index/$1');
and in the Controller i changed the index-function to
public function index($segment = null)
The URIs generated from the pagination now look like this:
https://DOMAIN.DE/usergroups/2
but it does not change anything in the entries and the pagination itself alway sticks to page 1.
I think, i can not use CI's built in library when switching to segment-URIs and thus i need to create a manual pagination.
Can somebody help me to fix this problem?
I currently had the same problem using segments in my pagination.
After much research I discovered that when you use segments associated with a group name in your case "test" you must assign the segment to the variable $ pager
$pager->setSegment(2, 'nameOfGroup');
You only need to change the first parameter with the segment number that you are using and the second with the name of the group that you are assigning.
It seems like there's a bug in Version 4.0.3. so it can't work out of the box. But i found a way to solve it:
The index-function needs to look like this:
public function index($page = 1)
and
within the Controller, the $data['usergroups'] need to look like this:
$data['usergroups'] = $model->paginate(5, 'test', $page, 2);
with 2 being the segment of the page-number in the URI.
Works like a charm.

cant get passed parameter by url in php

please help me, this is simple thing but I don't know why this still keep error for an hour,
on my view I've got :
<a href="admin/editProduct?idd=$id">
on my controller that directed from above :
public function editProduct(){
$data["id"] = $_GET['idd'];
$data["produk"] = $this->model_get->get_data_list(2);
//this below doesn't work either, i just want to past the parameter to my model
//$data["produk"] = $this->model_get->get_data_list($_GET['idd']);
$this->adminHeader();
$this->load->view("adminPages/editProduct", $data);
$this->adminFooter();
}
I can not use the array id. It keeps telling me undefined variable idd.
I don't know what to do anymore, please anyone help!
I am using Codeigniter framework
Change your view as:
<a href="admin/editProduct/<?php echo $id;?>">
And in the controller, either get the id as parameter,
public function editProduct($id) {
}
or as uri segment
public function editProduct() {
$id = $this->uri->segment(3);
}
Change your link (in view) with this
<a href="admin/editProduct/$id">
And change your controller as
public function editProduct($id) {
}
Then user $id inside your controller
Make the href link as follows:
...
And edit the controller like this:
public function editProduct($id){
...
$this->model_get->get_data_list($id);
}
Where $id will be the passed $id.
make
try this this works fine
public function editProduct()
{
$id=$this->uri->segment(3);
$data["produk"] = $this->model_get->get_data_list($id);
$this->adminHeader();
$this->load->view("adminPages/editProduct", $data);
$this->adminFooter();
}

Changing title of the page - determining whats the current page

I'm working on codeigniter and I wonder whats the best way to change title dynamically. Eg. title will change depending if you are on home page, single post page, category pages, etc.
The only solution i can think of is to make separate function and compare current URL ( from address bar ) with structure of the single post page, category page, home page
Something like this:
public function current_title() {
if($this->uri->segment(2) == 'post') {
// will return post title
}
if($this->uri->segment(2) == 'category') {
// will return archive title
}
if(current_url() == base_url()) {
// this is home page
}
If anyone worked with this before, any advice highly appreciated
I would not use the uri for this, but instead the controller and action name and the language class :
public function current_title()
{
$this->lang->load('titles.php', 'en');
return $this->lang->line(
$this->router->fetch_class().'.'.$this->router->fetch_method()
);
}
You will have a key like MyClass.myMethod for your translation. Just add your titles in your titles.php file :
$lang['MyClass.myMethod'] = "The title";
$lang['MyOtherClass.myOtherMethod'] = "The other title";
Read more about translation :
http://ellislab.com/codeigniter/user-guide/libraries/language.html
http://ellislab.com/codeigniter/user-guide/helpers/language_helper.html
//in the controller you should do like this:
class Home extends your_Controller {
public function __construct() {
parent:: __construct();
}
function index()
{
$this->data['pageTitle'] = 'Your page title';
$data['main_content'] = 'home';
$this->load->view('includefolder/viewname', $data);
}
}
This is how I do it:
$PHPFile = basename($_SERVER['PHP_SELF'],'.php');
switch ($PHPFile) {
case 'index': $PageTitle = 'Home'; break;
case 'products': $PageTitle = 'Products'; break;
case 'services': $PageTitle = 'Services'; break;
}
You can use string searches or whatever is needed. I use this method since I have the header of the page as a function in library.
As we have a controller function for each view so you can easily get function name from url
$this -> router -> fetch_module();
so you can work with it.

How do I use a controller within a controller?

I am using Kohana 3.2 and I am having problems calling the ouput of a controller in another controller.
What I want...
In some pages I have got a menu, and in others I don't. I want to use make use of the flexability of the HMVC request system. In the controller of a page I want to call another controller which is responsible for the creation of the menu.
What I have a the moment:
file menu.php:
<?php defined('SYSPATH') or die('No direct script access.');
class Controller_Menu extends Controller
{
private $_model = null;
public function __construct(Request $request, Response $response)
{
parent::__construct($request, $response);
$this->_model = Model::factory('menu');
}
public function action_getMenu()
{
$content = array();
$content['menuItems'] = $this->_model->getMenuItems();
// Render and output.
$this->request->response = View::factory('blocks/menu', $content);
//echo '<pre>'; print_r($this->request->response->render()); echo '</pre>'; die();
}
}
somepage.php
public function action_index()
{
$this->template->title = 'someTitle';;
$contentData['pageTitle'] = 'someTitle';
$contentData['contentData'] = 'someData';
#include the menu
$menuBlock = Request::factory('menu/getMenu')->execute();
$menuData = array('menu' => $menuBlock);
$this->template->menu = View::factory('pages/menu')->set('menu',$menuData);
$this->template->content = View::factory('pages/somePage', $contentData);
$view = $this->response->body($this->template);
$this->response->body($view);
}
If I uncomment the following line in menu.php, I see the menu rendered:
//echo '<pre>'; print_r($this->request->response->render()); echo '</pre>'; die();
So I guess that part is alright. The problem is in the following line in somepage.php:
$menuBlock = Request::factory('menu/getMenu')->execute();
This gives me back a response object. Whatever I do, I do not get the output in $this->template->menu.
$this->template->menu = View::factory('pages/menu')->set('menu',$menuData);
What must I do to have $this->template->menu contain the view, so I can use it correctly?
I hope this all makes sense. This is the way I would like to do it, but maybe I am completely on the wrong track.
I would do it this way:
class Controller_Menu extends Controller
{
public function action_build()
{
// Load the menu view.
$view = View::factory('navigation/menu');
// Return view as response-
$this->response->body($view->render());
}
}
In your controller get the menu as follows:
// Make request and get response body.
$menu = Request::factory('menu/build')->execute()->body();
// e.g. assign menu to template sidebar.
$this->template->sidebar = Request:.factory('menu/build')->execute()->body();
I would not use the __construct method in your controllers. Use before() instead, this is sufficient for most of the problems (for example auth):
public function before()
{
// Call aprent before, must be done here.
parent::before();
// e.g. heck whether user is logged in.
if ( !Auth::instance()->logged_in() )
{
//Redirect if not logged in or something like this.
}
}
I found the answer to my problem in less than an hour after asking.
I just forgot to put it here.
In somePage.php change :
$menuBlock = Request::factory('menu/getMenu')->execute();
$menuData = array('menu' => $menuBlock);
$this->template->menu = View::factory('pages/menu')->set('menu',$menuData);
To:
$this->template->menu = Request::factory('menu/getMenuBlock')->execute()->body();
And in menu.php change:
$this->request->response = View::factory('blocks/menu', $content);
To:
$request = View::factory('blocks/menu', $content);
$this->response->body($request);
I hope this will help someone else.

Categories