How do I add pagination to codeigniter - codeigniter

Below is how the ci controller looks like.
I'm just following tutorial from Youtube Channel.
How do you add pagination so the page only load 20 results per page ?
<?php
class Product_details extends CI_Controller{
function index(){
$this->load->library('pagination');
$this->load->model('product_model');
$data['userArray'] = $this->product_model->return_products();
$this->load->view('product_listing',$data);
}
}
View
<table>
<tr>
<th>ID</th>
<th>Product Name</th>
<th>Product Price</th>
<th>Product Image</th>
</tr>
<?php
foreach ($userArray as $key => $value) {
echo "<tr>
<td>".$value['id']."</td>
<td>".$value['post_id']."</td>
<td>".$value['price']."</td>
<td><img src=".$value['imageUrl']."/></td>
</tr>";
}
?>
</table>
Thank you

you can pass page number in the model.
Controller
<?php
class Product_details extends CI_Controller{
function index($pageNo){
$this->load->model('product_model');
$data['userArray'] = $this->product_model->return_products($pageNo);
$this->load->view('product_listing',$data);
}
}
Model
public function all($pageNo){
$pageNo -= 1;
$this->db->select("*")
->from('products')
->order_by('id',"ASC")
->limit(20, $pageNo * 20);
$query = $this->db->get();
return $query->result_array();

See the example how to add pagination.
Let's My controller is Dashboard.php and it's method is index.
Now configure pagination.
public function index()
{
$config['base_url'] = site_url('/dashboard/index/');
$config['total_rows'] = $this->dashboard_model->num_rows();
$config['per_page'] = 5;
$config['use_page_numbers'] = FALSE;
$this->pagination->initialize($config);
$data['data'] = $this->dashboard_model->all_blog($config['per_page'], $this->uri->segment(3));
$this->load->view("/dashboard/blog", $data);
}
Model is Dashboard_model.php
public function all_blog($limit, $offset)
{
$this->db->from('blogs');
$this->db->select('*');
$this->db->order_by("created_at", "desc");
$q = $this->db->get();
$data = $q->result_array();
return $data;
}
public function num_rows()
{
$this->db->from('blogs');
$this->db->select('*');
$this->db->order_by("created_at", "desc");
$this->db->limit($limit, $offset);
$q = $this->db->get();
$data = $q->num_rows();
return $data;
}
Now it's my view blog.php
<div class="table-responsive">
<table class="footable table table-stripped toggle-arrow-tiny" data-page-size="8" data-filter=#filter; id="filter">
<thead>
<tr>
<th></th>
<th>S.No</th>
<th>Title </th>
<th>Blog Image</th>
<th>Added For</th>
</tr>
</thead>
<tbody>
<?php
$count = $this->uri->segment(3, 0);
foreach ($data as $key) :
?>
<tr>
<td><input type="checkbox" class="i-checks" name="input[]"></td>
<td><?php echo ++$count; ?></td>
<td><?php echo $key['blog_title']; ?></td>
<td><img src="<?php echo $key['blog_image']; ?>" style="width: 150px; height: 80px" /></td>
<td><?php echo $key['user_type']; ?></td>
</tr>
<?php endforeach?>
</tbody>
</table>
</div>
<?php
echo $this->pagination->create_links();
?>

Related

Laravel Nested #foreach By 2 Different Model in View

Model
// Relationship in \App\FatherRegistrars and \App\MotherRegistrars and \App\GuardianMaleRegistrars \App\GuardianFemaleRegistrars
public function student_registrars()
{
return $this->belongsToMany('App\StudentRegistrars')->withTrashed();
}
Controller
public function index(Request $request)
{
$dataFathers = \App\FatherRegistrars::get();
$dataMothers = \App\MotherRegistrars::get();
$dataGM = \App\GuardianMaleRegistrars::get();
$dataGF = \App\GuardianFemaleRegistrars::get();
// manual pagination using code attached in AppServiceProvider.php
$data = $dataFathers->toBase()->merge($dataMothers)->paginate($items);
return view('parents-guardians-registrars.index', compact('data', 'dataFathers', 'dataMothers', 'dataGM', 'dataGF'))->withItems($items);
}
View
#foreach($data as $var)
<tr>
<td style="text-align:center;">
<input type="checkbox" id="select" class="sub_chk" data-id="{{$var->id}}" value="{{$var->id}}" name="selected_values[]"/>
</td>
<td>{{$var->id }}</td>
<td>{{$var->name}}</td>
<td>{{$var->email}}</td>
<td>
<?php $elements = array(); ?>
#foreach($var->student_registrars as $category)
<?php $elements[] = ' '.$category->name.' '; ?>
#endforeach
<?php echo implode(',<br>', $elements); ?>
</td>
<td>
// Second foreach should be here
</td>
<td>
Detail
</td>
#endforeach
// Second foreach
#foreach($dataGM as $var2)
<tr>
<td>
<?php $elements = array(); ?>
#foreach($var2->student_registrars as $category)
<?php $elements[] = ' '.$category->name.' '; ?>
#endforeach
<?php echo implode(',<br>', $elements); ?>
</td>
</tr>
#endforeach
</tr>
And the result for code above is:
I have a little problem related multiple foreach in one view. It's actually just a simple problem but I am stuck here. Any body can solve it?
Should I use partial view to do this?
This may not exactly work (not tested or verified), but you can give something like this a try:
#foreach($data as $var)
<tr>
<td style="text-align:center;">
<input type="checkbox" id="select" class="sub_chk" data-id="{{$var->id}}" value="{{$var->id}}" name="selected_values[]"/>
</td>
<td>{{$var->id }}</td>
<td>{{$var->name}}</td>
<td>{{$var->email}}</td>
<?php $elements = array(); ?>
#foreach($var->student_registrars as $i => $category)
<td>
<?php $elements[] = ' '.$category->name.' '; ?>
<?php echo implode(',<br>', $elements); ?>
</td>
<td>
<?php $elements2 = array(); ?>
#foreach($var2->student_registrars[$i] as $category)
<?php $elements2[] = ' '.$category->name.' '; ?>
#endforeach
<?php echo implode(',<br>', $elements2); ?>
</td>
#endforeach
<td>
Detail
</td>
</tr>
#endforeach
The problem you have is that there is no direct association $data and $dataGM. You should try and use Relationships so that the data needed for $dataGM can be accessed as a relationship from $data, e.g.
$children = $data[$i]->children;
$adopted = $data[$i]->adopted_children;
Then you can loop directly on these items instead of having to create multiple variables.

How can I use searchbar using ajax in laravel?

In laravel, I am using search bar in list view, It will search from the record using ajax and display me the output.
But it's now working, when i write any text in search bar I didn't get any output. All records displays as it is.
My database in mongoDb, and i am coding in laravel.
Here is my view file code.
view
<div class="table-responsive m-t-40">
<div class="form-group">
<input type="text" name="search" id="search" class="form-control" placeholder="Search Department" />
</div>
<table class="table table-bordered table-striped ">
<thead>
<tr>
<th>Department Name</th>
<th>Created By</th>
<th>Created On</th>
#if (App\User::isPermitted(['edit_department', 'update_department', 'delete_department']))
<th>Action</th>
#endif
</tr>
</thead>
<tbody>
#if($listOfDepartment != null)
#foreach($listOfDepartment as $departmentList)
<tr>
<td>{{$departmentList->nameOfDepartment}}</td>
<td>{{$departmentList->createdBy}}</td>
<td>{{$departmentList->created_at}}</td>
#if (App\User::isPermitted(['edit_department', 'update_department', 'delete_department']))
<td>
<i class="fa fa-edit fa-lg" style="color:#0066ff" aria-hidden="true"></i> 
<i class="fa fa-trash fa-lg" onclick="delete_user(this); return false;" style="color:red" aria-hidden="true"></i>
</td>
#endif
</tr>
#endforeach
#endif
</tbody>
</table>
</div>
script
<script>
$(document).ready(function(){
fetch_customer_data();
function fetch_customer_data(query = '')
{
$.ajax({
url:"{{ route('list_department') }}",
method:'GET',
data:{query:query},
dataType:'json',
success:function(data)
{
$('tbody').html(data.table_data);
}
})
}
$(document).on('keyup', '#search', function(){
var query = $(this).val();
fetch_customer_data(query);
});
});
</script>
and here is my code of controller file
namespace App\Http\Controllers;
use App\Department;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Schema;
public function listDepartment(Request $request)
{
$listOfDepartment = Department::all();
if($request->ajax())
{
$output = '';
$query = $request->get('query');
if($query != '')
{
$data = Schema::table('department')
->where('nameOfDepartment', 'like', '%'.$query.'%')
->orWhere('createdBy', 'like', '%'.$query.'%')
->get();
}
else
{
$data = Schema::table('department')
->orderBy('nameOfDepartment', 'asc')
->get();
}
$total_row = $data->count();
if($total_row > 0)
{
foreach($data as $row)
{
$output .= '<tr>
<td>'.$row->nameOfDepartment.'</td>
<td>'.$row->createdBy.'</td>
</tr>';
}
}
else
{
$output = '
<tr>
<td align="center" colspan="5">No Data Found</td>
</tr>
';
}
$data = array(
'table_data' => $output,
'total_data' => $total_row
);
echo json_encode($data);
}
return view('pages.department', compact('listOfDepartment'));
}

View from model and controller in codeigniter

**Controller file i have form_ctrl.php and code given below**
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class form_ctrl extends CI_Controller {
public function index()
{
//$this->load->view('welcome_message');
$this->load->helper(array('form', 'url'));
$this->load->library('form_validation');
$this->load->model('data_model');
//$this->form_validation->set_rules('name', 'Username', 'required');
$this->form_validation->set_rules('name', 'name','required|min_length[5]|max_length[12]');
$this->form_validation->set_rules('pass', 'Password', 'required',
array('required' => 'You must provide a %s.')
);
$this->form_validation->set_rules('email', 'Email', 'required');
$this->form_validation->set_rules('mobile', 'Mobile', 'required');
$this->form_validation->set_rules('address', 'Address','required|min_length[5]');
if ($this->form_validation->run() == FALSE)
{
$this->load->view('table');
}
else
{
$this->load->view('results');
$name=$this->input->post('name');
$pass=$this->input->post('pass');
$email=$this->input->post('email');
$mobile=$this->input->post('mobile');
$address=$this->input->post('address');
$data = array(
'name' =>$name ,
'pass' => $pass,
'email' => $email,
'mobile' => $mobile,
'address' => $address
);
$this->data_model->insert_fun('form', $data);
}
}
function GetAll()
{
$this->load->model('emp_model');
$data['query']=$this->emp_model->emp_getall();
$this->load->view('emp_viewall',$data);
}
}
**model file i have data_model.php**
<?php
class data_model extends CI_Model {
function __construct() {
parent::__construct ();
}
public function insert_fun($tableName,$data){
return $this->db->insert($tableName, $data);
}
function emp_getall()
{
$this->load->database();
$query=$this->db->get('form');
return $query->result();
}
}
?>
view file i have results.php
<html>
<head>
<title>My Form</title>
</head>
<body>
<table width="100%" border="1">
<tr>
<td>Name</td>
<td>Email</td>
<td>Mobile</td>
<td>Address</td>
<td>Action</td>
</tr>
<?php
foreach($query as $row)
{
print_r($row);exit;
}
?>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
</table>
</body>
</html>
data is inserting properly but view not showing the database fields it means IN model file function (function emp_getall()) orin controller file (function GetAll()) is not working give me the solution where error in this code...
function GetAll()
{
$this->load->model('emp_model');
$data['query']=$this->emp_model->emp_getall();
$this->load->view('results',$data);
}
you wrong view call check this
<html> <head>
<title>My Form</title>
</head>
<body>
<table width="100%" border="1">
<tr>
<td>Name</td>
<td>Email</td>
<td>Mobile</td>
<td>Address</td>
<td>Action</td>
</tr>
<?php
foreach($query as $row) : ?>
<tr>
<td><?php echo $row->name;?></td>
<td><?php echo $row->email;?></td>
<td><?php echo $row->mobile;?></td>
<td><?php echo $row->address;?></td>
<td><?php echo $row->action;?></td>
</tr>
</table>
<?php endforeach ?>
</body>
</html>
try this once .............

Laravel Eloquent Group By Dates

i was trying to search on how i can create the same result on this image below on my laravel .I was trying to group it by dates. All the dates that are on the same month will be merge on a single row.
what i accomplished so far. i cannot merge the dates that has the same months.
Does any one know how i can accomplished this? thanks
<table>
<thead>
<tr>
<th>Test Type</th>
<?php
$types = Tblreporttype::all();
?>
#foreach($types as $type)
<?php
$dates = Tblreportdate::with('tblreporttype')
->groupBy('fDate')
->where('tblreporttype_id', '=', $type->id)
->get();
?>
#foreach($dates as $date)
<?php
$convert = $date->fDate;
$my_date = date('M/y', strtotime($convert));
?>
<th width="100">
<?php
if($my_date == $my_date) {
echo $my_date;
}
?>
</th>
#endforeach
#endforeach
</tr>
</thead>
<tbody>
<?php
$dates = Tblreportdate::with('tblreporttype')
->groupBy('fDate')
->get();
?>
<?php
$types = Tblreporttype::all();
?>
#foreach($types as $type)
<tr>
<td width="200">{{ $type->fType }}</td>
#foreach($dates as $date)
<?php
$convert = $date->fDate;
$my_date = date('d', strtotime($convert));
?>
<td width="100">
<?php
if($date->tblreporttype->id == $type->id) {
echo $my_date;
} else {
echo " ";
}
?>
</td>
#endforeach
</tr>
#endforeach
</tbody>
</table>
This is the output

Displaying serial numbers with query result

I am trying to fetch data from my database and when I display it I want to show serial numbers (Just like a list) , example:
**Serial Number** Name Country
1. John USA
2. Srijon UK
I have tried something with PHP Loops, but I couldn't make it work. Would you please kindly help me? please note that by serial numbers I don't mean values retrieved from database.
Thanks in Advance :)
Here's my Model
//Function To Create All Batch List
function batch_list($perPage,$uri) {
$this->db->select('*');
$this->db->from('batch');
$this->db->join('teacher', 'batch.batchinstructor = teacher.teacherid');
$this->db->order_by('batchid','DESC');
$getData = $this->db->get('', $perPage, $uri);
if($getData->num_rows() > 0)
return $getData->result_array();
else
return null;
}
//End of Function To Create All Batch List
Here's mY Controller
function index(){
$this->load->library('pagination');
$config['base_url'] = base_url().'batchlist/index';
$config['total_rows'] = $this->db->get('batch')->num_rows();
$config['per_page'] = 20;
$config['num_links'] = 20;
$config['full_tag_open'] = '<div class="pagination" align="center">';
$config['full_tag_close'] = '</div>';
$this->pagination->initialize($config);
$this->load->model('mod_batchlist');
$data['records']= $this->mod_batchlist->batch_list($config['per_page']
,$this->uri->segment(3));
$data['main_content']='view_batchlist';
$this->load->view('includes/template',$data);
}
Here's My View
<?php if(count($records) > 0) { ?>
<table id="table1" class="gtable sortable">
<thead>
<tr>
<th>Batch Name</th>
<th>Class</th>
<th>Batch Instructor</th>
<th>Edit/Delete</th>
</tr>
</thead>
<tbody>
<?php foreach ($records as $row){ ?>
<tr>
<td><?php echo $row['batchname'];?> </td>
<td><?php echo $row['class'];?></td>
<td><?php echo $row['teachername'];?></td>
<td> <img src="<?php echo base_url(); ?> support/images/icons/edit.png" alt="Edit" />
<img src="<?php echo base_url(); ?>support/images/icons/cross.png" alt="Delete" />
</td>
</tr>
<?php } ?>
</tbody>
</table>
<?php } ?>
<div class="tablefooter clearfix">
<div class="pagination">
<?php echo $this->pagination->create_links(); ?>
</div>
</div>
<?php if(count($records) > 0) { ?>
<table id="table1" class="gtable sortable">
<thead>
<tr>
<th>Serial</th>
<th>Batch Name</th>
<th>Class</th>
<th>Batch Instructor</th>
<th>Edit/Delete</th>
</tr>
</thead>
<tbody>
<?php $i = $this->uri->segment(3); foreach ($records as $row){ $i++; ?>
<tr>
<td><?php echo $i; ?>.</td>
<td><?php echo $row['batchname'];?> </td>
<td><?php echo $row['class'];?></td>
<td><?php echo $row['teachername'];?></td>
<td> <img src="<?php echo base_url(); ?> support/images/icons/edit.png" alt="Edit" />
<img src="<?php echo base_url(); ?>support/images/icons/cross.png" alt="Delete" />
</td>
</tr>
<?php } ?>
</tbody>
</table>
<?php } ?>
<div class="tablefooter clearfix">
<div class="pagination">
<?php echo $this->pagination->create_links(); ?>
</div>
</div>
In my case the fourth and fifth parameters where page number and rows per page respectively
ie: example.com/category/page/1/10
first page with 10 rows per page.
so in this case just use this before the loop
$i = $this->uri->segment(4)? (
$this->uri->segment(4) + $this->uri->segment(5)? $this->uri->segment(5):0
)
:0;
and from inside the loop just increment the value of i.
foreach ($result_obj as $key => $value)
{
$i++;
...
}
Try this..work like this..1,2,3,4,5
$i = 0
while($condition)
{
echo '<td>'.$i++.'</td>';
}

Resources