How do I make a function available to several CodeIgniter methods? - codeigniter

CodeIgniter 2.1.2
I have a class that contains two methods, for the purpose of this questions showone and view. The latter returns all items of a small database and can also perform a search. The other one is for permalinks like domain.com/showone/firstname-lastname
<?php
class Pages extends CI_Controller {
public function view($page)
{
//this includes a mysql search
}
public function showone($slug)
{
//abbreviated version:
$query = "SELECT * FROM mytable WHERE slug = '" . $slug . "'";
$result = $this->db->query($query);
if ($result->num_rows() == 0)
{
//here is where I'd like to use the same search that I used in showall
}
else
{
//show the one item
}
}
} //class
?>
So if a user decides to directly enter a URL that doesn't return anything from the database, I would like to direct him to search results instead of showing a 404.
So how do I set up a function searchdatabase($query) to be used by both showone and view?

You can use your controller functions inside your controller:
public function view($page)
{
$this->showone($slug);
}

Define that function in your model, load your model and then call the model->method.
<?php
//Your Model would look something like this.
class Search_Model extends CI_Model {
public function __construct(){
parent::__construct();
}
public function showone($slug)
{
//abbreviated version:
//Its best to use active record for building your queries
$this->db->where->('slug', $slug);
$result = $this->db->get('mytable');
if ($result->num_rows() == 0)
{
//here is where I'd like to use the same search that I used in showall
}
else
{
//show the one item
}
}
} //class
And then in your controller you would do this:
<?php
//Your Controllerwould look something like this.
class Index extends CI_Controller {
public function __construct(){
parent::__construct();
//model will be loaded for each method.
//if you're going to use this model across several controllers
//its best to autoload it, set that in autoload.php under /app/config
$this->load->model('search_model');
}
public function index(){
$searchResults = $this->search_model->showone('slugone');
}
Update
I just realized you are wanting to show all results if no results were returned. In which case you would perform that logic in your model as well..
In your conditional statement you would do the following:
if ($result->num_rows() == 0)
{
return $this->showall();
}
else
{
return $this->view($slug);
}
}
your showall() and view() methods would return $result->result();

Related

Laravel 5.7 getting all the siblings for each child

I wonder how to get all the sibling that a child have in laravel model ?
I know i can use this $siblings = \App\Child::all()->where('parent_id', $parent_id)->where('id', $id); to get all the child siblings, but I want to know if I can do the other way or more cleanest way?
So you can call this in the blade view $child->siblings->full_name something like that.
But I wonder how to use it something like this in the model.php
public function parent()
{
return $this->belongsTo(User::class);
}
with only using the belongsTo or hasMany function maybe if it's possible?
Sorry I'm not good with english so I don't know what it's called so I can search it on google.
Edit:: Adding Child.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Carbon\Carbon;
class Child extends Model
{
protected $guarded = [];
protected $dates = [
'birthdate',
'father_birthdate',
'mother_birthdate',
'guardian_birthdate',
];
public function parent()
{
return $this->belongsTo(User::class);
}
// I want to call this function only using $child->siblings (this one will show all the siblings)
// without passing the parent id
// to make it cleaner
public function siblings($parent_id)
{
return $this->all()->where('parent_id', $parent_id);
}
public function getAgeAttribute()
{
return Carbon::parse($this->attributes['birthdate'])->age;
}
public function getFullNameAttribute()
{
return $this->attributes['first_name'] . ' ' . $this->attributes['last_name'];
}
}
There are 2 ways you could do this.
1 creating the below method:
public function sibling()
{
return $this->belongsTo(User::class)->where('parent_id', $this->parent_id);
}
2 using a single Query:
$siblings = \App\Child::where('parent_id', $parent_id)->get();
Hope this helps
Update
A third way is:
public function scopeSiblings($query, $parent_id) {
return $query->where('parent_id', $parent_id)->get();
}

call the another function within a function

In laravel I want to call a function within function to make recursive.I caught the route error.how to call the function 'recursive in tableFetch'
class queryTest extends Controller
{
public function tableFetch() {
recursive();
}
function recursive(){
//condition
}
}
I want to do it for check the manager of the given person and then get the manager of the fetched value in query so need to do it recursive
A controller is not a good place for this. Instead, manage it in your Person Model(or whatever you have).
Everyone has a manager. So, your model has HasOne relation to itself.
Person Model:
public function manager()
{
return $this->hasOne(Person::class, 'manager_id');
}
Now if you need to check the manager of given person untill you meet a certain condition you can do it inside the model and get the result in the controller.
public function checkManager()
{
$manager = $this->manager
if (check manager)
return $manager;
//check for the last manager
return $this->manager ? $this->checkManager() : null;
}
Inside controller
function index()
{
$person = Person::find($id);
$manager = $person->checkManager();// this will do the recursive you need
}
Do something like this
class queryTest extends Controller
{
public function tableFetch() {
$this->recursive();
}
function recursive(){
//condition
}
}
you need to ask more precise details about your needs, because Laravel has some complications.
try doing this :
class queryTest extends Controller
{
public function tableFetch() {
$this->recursive();
}
public function recursive() {
//condition
}
}

`CI` return wrong value

I have no idea why my CI return wrong value from phpMyAdmin
Model :
<?php
class Post extends CI_Model
{
function __construct()
{
parent::__construct();
}
function getallpost()
{
return $this->db->get('post');
}
}
?>
And
Controller :
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Postc extends CI_Controller {
function index()
{
$this->load->model('post');
$posts=$this->post->getallpost();
echo '<pre>';
print_r($posts);
}
}
?>
enter image description here
You code is not giving you any error, it is doing exactly what you are asking it to do. Perhaps you need to be specific about the information you want to get. You see in your model
function getallpost()
{
return $this->db->get('post');
}
The above function will return you an object. If you want to get an array you need to write
return $this->db->get('post')->result_array();
And make sure you have some data in your post table to print For learning more about query database you should read Codeigniter's Query Builder Class
Change your Model Code
<?php
class Post extends CI_Model
{
function __construct()
{
parent::__construct();
}
function getallpost()
{
$query = $this->db->get('post');
if($query->num_rows() > 0)
{
return $query->result();
}else{
return false;
}
}
}
If you want to get return your result as as array then use
return $this->db->get('post')->result_array();
And if you want to get return your result as object then use
return $this->db->get('post')->result();

Codeigniter get specific record in table

I practicing CI and loop through all records in a view and produces each link as below:
sitename.com/products/2
where 2 is id of certain product, I want to click on the link and get this product information in product page, how can I create a model to retrieve specific record?
Model:
class Db_model extends CI_Model {
public function __construct()
{
$this->load->database();
}
public function getProduct($id) {
$query = $this->db->get_where('tbl_product', array('id' => $id));
return $query->result();
}
}
Controller:
class Products extends CI_Controller {
public function __construct()
{
parent::__construct();
$this->load->model('db_model');
}
public function index()
{
$data['rows'] = $this->db_model->getProduct($id);
$this->load->view('product', $data);
}
}
Thanks for help.
Your index function doesn't take $id as a parameter, So you need to modify your index function, Use the following index function, which I've edited.
public function index($id)
{
$data['rows'] = $this->db_model->getProduct($id);
$this->load->view('product', $data);
}

CodeIgniter routing issue, advice how to do it

I'm not CI programmer, just trying to learn it. Maybe this is wrong approach, please advice.
my controller(not in sub directory) :
class Users extends CI_Controller {
function __construct() {
parent::__construct();
}
public function index($msg = NULL) {
$this->load->helper(array('form'));
$data['msg'] = $msg;
$this->load->view('user/login' , $data);
}
public function process_logout() {
$this->session->sess_destroy();
redirect(base_url());
}
}
And a route for login :
$route['user/login'] = 'users/index';
Problem is when I wanna logout, it shows me 404 because I do not have it in my route :
$route['user/process_logout'] = 'users/process_logout';
and in my view I put logout
When I add that, it works, and that is stuppid to add a route for everything. What I'm I doing wrong, please advice.
Thank you
Don't know why you are trying to implement login feature in index() function. However since you said you are learning CI I'm telling something about _remap() function.
Before that. You can try the following routing:
$route['user/:any'] = 'users/$1';
$route['user/login'] = 'users/index';
If you want to take value immediately after controller segment you need to use _remap() function and this function may be solve your routing problem, i mean you don't need to set routing. Lets implement your code controller 'users' using _remap() function.
class Users extends CI_Controller {
private $sections = array('login', 'logout');
function __construct() {
parent::__construct();
}
public function _remap($method)
{
$section = $this->uri->segment(2);
if(in_array($section, $this->sections))
call_user_func_array(array($this, '_'.$section), array());
else show_404(); // Showing 404 error
}
private function _login()
{
$msg = $this->uri->segment(3);
$this->load->helper(array('form'));
$data['msg'] = $msg;
$this->load->view('user/login' , $data);
}
public function _logout() {
$this->session->sess_destroy();
redirect(base_url());
}
}

Resources