Laravel 5.5 recursive function to create menu - laravel

I have created a mysql table as below:
id | menuname | parentid
---+-------------------+---------
1 | dashboard | 0
2 | Content | 0
3 | Home Page Content | 2
4 | Banners | 2
5 | Settings | 0
6 | Block Content | 3
7 | Site Content | 3
So that the menu structure will look like:
dashboard
Content
Home Page Content
Block Content
Site Content
Banners
Settings
I have the controller:
public function index() {
$data = array();
$permissionRecord = Permission::all();
$this->categoryTree($permissionRecord);
dd('-end-);
$data['permissionRecord'] = $permissionRecord;
return view('Administrator.permission.permissionAdd',$data);
}
function categoryTree($permissionRecord, $parent_id = 0, $sub_mark = '')
{
foreach($permissionRecord as $row) {
echo $sub_mark.$row->name;
$this->categoryTree($permissionRecord, $row->id, $sub_mark.'---');
}
}
But this show the data :
Dashboard---Dashboard------Dashboard---------Dashboard------------Dashboard---------------Dashboard------------------Dashboard---------------------Dashboard------------------------Dashboard---------------------------Dashboard------------------------------Dashboard---------------------------------Dashboard------------------------------------Dashboard
Please note, I dd() inside the controller and did not passed the data to the view.

You've not accounted for the parent ID:
function categoryTree($permissionRecord, $parent_id = 0, $sub_mark = '')
{
foreach($permissionRecord as $row) {
if ($row->parentid == $parent_id) {
echo $sub_mark.$row->name;
$this->categoryTree($permissionRecord, $row->id, $sub_mark.'---');
}
}
}
Try that and see what happens - Note I've wrapped the recursive function call in an if() that checks if the current records parentId is equal to the parent ID passed into the method.
To get it to display the items in an indented list:
public function categoryTree($permissionRecord, $parent_id = 0)
{
$html = '<ul>';
foreach($permissionRecord as $row) {
if ($row->parentid == $parent_id) {
$html .= '<li>' . $row->menuname;
$html .= $this->categoryTree($permissionRecord, $row->id, $html);
$html .= '</li>';
}
}
$html .= '</ul>';
return $html;
}
Then just call:
$html = $this->categoryTree($permissionRecord);
Example of it working with a unit test

Related

How do I fetch this from two different table in codeigniter

I have two tables state and city
state table has two column
state_id | state_name
---------|-----------
1 | Alabama
2 | Alaska
3 | Arizona
and City table has two column as well
state_name | city_name
-----------|----------
1 |
1 |
1 |
2 |
2 |
3 |
Controller
function city()
{
$data = array();
$data['states']=$this->state_model->state_query();
$data['cities']=$this->cities_model->cities_query();
$this->load->view('city', $data);
}
Model
public function state()
{
$this->db->select('state_name');
$this->db->from('state');
$this->db->join('city', 'city.state_name = state.state_name');
$result = $this->db->get();
}
View
<?php foreach ($cities as $city) { ?>
<?php echo $city->city_name; ?>
<?php echo $city->state_name; ?>
<?php } ?>
the above code is the controller, model, and view respectively. The issue is that I want to echo state_name but not working, the city name is displaying as expected. Please, I need suggestion on what to do.
Your Model Should Be:
public function state()
{
$this->db->select('s.state_name as state,c.city_name as city, c.state_name as state_id');
$this->db->from('state as s');
$this->db->join('city as c', 'c.state_name = s.state_id ');
$result = $this->db->get();
$data = $result->result_array();
if(isset($data) && !empty($data))
{
return $data;
} else {
return FALSE;
}
}
Your Controller Should be:
public function city()
{
$this->load->model('your_model');
$city_state_data = $this->your_model->state();
// I have just added example of getting data from model to controller
// and then passing it to view. You need to use it as you need
$this->load->view('your_view', ['city_state_data' => $city_state_data]);
}
View:
<?php foreach ($city_state_data as $single_city_state) { ?>
<?php echo $single_city_state['state']; ?>
<?php echo $single_city_state['city']; ?>
<?php } ?>
Model
public function state()
{
$this->db->select('state.state_name as state_tbl1, city.state_name as state_tbl2, city.city_name');
$this->db->join('city', 'city.state_name = state.state_name');
$result = $this->db->get('state');
return $result->result();
}
Controller
function city()
{
$data['states']=$this->state_model->state();
$this->load->view('city', $data);
}
View
<?php foreach ($states as $city) {
echo $city->city_name;
echo $city->state_tbl1;
echo $city->state_tbl2;
} ?>

links in pagination in codeigniter

in my view page,in the 1st form i have 2 select drop down...in the 1st drop down i am populating the value default from the controller...when u onchange the value in the 1st drop down,the selected value is passed to controller via javascript..in the controller,i get that 1st drop down value and load model and get value from model for the 2nd drop down and post it to view page...when u select the 2nd drop down value and click submit,the both drop down values are posted to controller after form validation and load model and get user information from the database and post it back again to view page ...this is the scenario for my view page..so,u can change the above both select drop down to get informations in the 2nd form in the same view page..now when i did pagination for my 2nd form user information,i am getting the links and data perfectly according to the limits and offsets..but,i am unable to retrieve the information when i click 2nd,3rd,4th..and rest on links while the informations are being posted from controller..so what can i do now?,,here is my code after i get both drop down values in the controller..
in my controller..
public function get_form_dept()
{
$this->load->helper(array('form', 'url'));
$this->load->library("pagination");
$this->load->library('form_validation');
$this->form_validation->set_rules('formation','Formation','required|required');
if($this->form_validation->run()== false) {
$this->viewstudent();
} else {
$config['base_url'] = base_url() . 'Incite/get_form_dept';
if($this->input->post('formation') == 1 && $this->input->post('department') == 1){
$config['total_rows'] = $this->db->get('user')->num_rows();
} else {
//$this->db->select('list_formation');
$query = $this->db->get_where('formation',array('id' => $this->input->post('formation')));
// echo $this->db->get_where('formation',array('id' => $this->input->post('formation')));
$row = $query->result();
foreach($row as $key) {
$get_formation = $key->list_formation;
echo $get_formation ."<br>";
}
$query1 = $this->db->get_where('department',array('id' => $this->input->post('department')));
$row1=$query1->result();
foreach($row1 as $key) {
$get_dept=$key->list_department;
echo $get_dept . "<br>";
}
//$array = array('formation' => $get_formation, 'department' => $get_dept);
//$config['total_rows']=$this->db->get('user',$array)->num_rows();
$query = $this->db->query("SELECT * FROM user where formation='$get_formation' and department='$get_dept'");
echo "SELECT * FROM user where formation='$get_formation' and department='$get_dept'" . "<br>";
$config['total_rows']=$query->num_rows();
//echo $row ."<br>";
//echo $row=$this->db->get('user',$array)->num_rows();
}
$config['per_page'] = 5;
//$config['uri_segment'] = 3;
//$choice = $config['total_rows'] / $config['per_page'];
// $config['num_links'] = round($choice);
$config['num_links'] = 2;
//$config['use_page_numbers'] = TRUE;
$config['suffix']= '?' . http_build_query($_GET, '', "&");
$this->pagination->initialize($config);
if($this->input->post('formation')== 1 && $this->input->post('department') == 1) {
// $this->db->limit($limit, $start);
$query_result = $this->db->get('user',$config['per_page'], $this->uri->segment(3));
$data['result']= $query_result->result();
} else {
$query = $this->db->get_where('formation',array('id' => $this->input->post('formation')));
$row = $query->result();
foreach($row as $key) {
$get_formation = $key->list_formation;
}
$this->db->where('id', $this->input->post('department'));
$query1 = $this->db->get('department');
$row1=$query1->result();
foreach($row1 as $key) {
$get_dept=$key->list_department;
//echo $get_dept;
}
$array = array('formation' => $get_formation, 'department' => $get_dept);
//$this->db->limit($limit, $start);
//$query = $this->db->get_where('user',$array);
$query_result=$this->db->get_where('user',$array,$config['per_page'], $this->uri->segment(3));
$data['result'] = $query_result->result();
}
$this->load->model('model_select_formation');
$data['formation'] = $this->model_select_formation->modelselectformation();
// query to fetch department
$data['dept']=$this->model_select_formation->get_department($data['formation_id']);
$data['formationid'] = $this->input->post('formation');
$data['departmentid'] = $this->input->post('department');
$this->load->view('viewstudent',$data);
}
}

How to make dynamic drop down in php?

I want to make a dynamic drop down in CI.I had done it in CI by directly passing the values from model With its design by concatenation the html.. But now i want it without the html i.e. the function just only should return the array ...
my before function was something like this...
function category() {
$sql = $this->db->query("select * from ss_category where parent_id='0'");
$result = $sql->result();
//print_r($result);die();
$output = array();
foreach ($result as $ra) {
$output=$this->get_child($ra->cat_id);
}
//print_r($output);die();
return $output;
}
function get_child($parent_id) {
//echo "select * from ss_category where parent_id=" . $parent_id;
$sql = $this->db->query("select * from ss_category where parent_id=" . $parent_id);
$r = $sql->result();
if (!empty($r)) {
foreach ($r as $s) {
$this->get_child($s->cat_id);
}
//print_r($child);
}
//print_r($r);
}
I want to make drop down something like this..
-parent 1
-child 1
-subchild 1
-child 2
-child 3
-subchild 1
-parent 2
-child 1
My table structure is like this..
+---------------------------------------------------------------+
| cat_id category_name cat_slug parent_id level description |
+---------------------------------------------------------------+
| 1 Elecotronics Electronics 1 description |
+---------------------------------------------------------------+
function parent_sort($categories)
{
foreach($categories as $item)
$childs[$item->parent_id][] = $item;
foreach($categories as $item)
if (isset($childs[$item->category_id]))
$item->childs = $childs[$item->category_id];
return $childs[0];
}

codeigniter 2.1.3 multilanguage website how to?

codeigniter 2.1.3 multilanguage website how to ?
i have on /language/english and /language/french
this french
$lang['user_login'] = 'Connecté';
this english
$lang['user_login'] = 'Login';
the language file its called user_lang.php
on the controller contructor i have this :
$this->load->helper('url');
$this->load->helper('language');
on the function index i have this :
public function index()
{
$this->lang->load('user', 'french');
....
on the view i have the following :
<div class="pageTitle"><?php echo $this->lang->line('user_login');?></div>
/*
| -------------------------------------------------------------------
| Auto-load Language files
| -------------------------------------------------------------------
| Prototype:
|
| $autoload['language'] = array('lang1', 'lang2');
|
| NOTE: Do not include the "_lang" part of your file. For example
| "codeigniter_lang.php" would be referenced as array('codeigniter');
|
*/
$autoload['language'] = array('user');
the question is that the website is working its going to the user_lang.php
to get the word login
but only goes to the english file
$this->lang->load('user', 'french');
iam doing this above , and its not working never reads the french file
i have another question , how can i get this working so i can switch languages with a anchor or href
thanks
Pedro
I would create a function like:
function language($language){
$language = urldecode($language);
switch($language){
case "French":
$this->session->set_userdata('lang_id', 2);
$this->session->set_userdata('lang_name', 'french');
redirect('/', 'refresh');
break;
case "Russian":
$this->session->set_userdata('lang_id', 3);
$this->session->set_userdata('lang_name', 'russian');
redirect('/', 'refresh');
break;
default: //default is English
$this->session->set_userdata('lang_id', 1);
$this->session->set_userdata('lang_name', 'english');
redirect('/', 'refresh');
break;
}
}
And I would change languages navigating to: http://www.domain.com/controller/language/French
Then in every controller or in constructor of each controller class I would check for the lang_id and lang_name session. If sessions are set, I would use them. Else the default language from the config will automatically load. For example:
$lang = $this->session->userdata('lang_name');
if(!isset($lang)){ //load default language
$this->lang->load('home');
$data = array(
'title' => lang('page_title')
);
//etc etc
}else{ //load language from session
$this->lang->load('home', $this->session->userdata('lang_name'));
$data = array(
'title' => lang('page_title')
);
//etc etc
}
in my welcome controller
public function french()
{
$this->session->set_userdata('lang_id', 2);
$this->session->set_userdata('lang_name', 'french');
$DContent['page_details'] = array('page_title' => 'Index of onplans');
$Dheader = array();
$Dsidebar = array();
$Dfooter = array();
$Dmeta = array('meta_title'=>'Welcome to onplans','meta_descricao'=>'onplans');
$this->template->write_view('meta', 'html/meta', $Dmeta, true);
$this->template->write_view('header', 'html/header', $Dheader, true);
$this->template->write_view('content', 'onplans/frenchset', $DContent,true);
$this->template->write_view('sidebar', 'html/sidebar');
$this->template->write_view('footer', 'html/footer');
$this->template->render();
}
public function english()
{
$this->session->set_userdata('lang_id', 3);
$this->session->set_userdata('lang_name', 'english');
$DContent['page_details'] = array('page_title' => 'Index of onplans');
$Dheader = array();
$Dsidebar = array();
$Dfooter = array();
$Dmeta = array('meta_title'=>'Welcome to onplans','meta_descricao'=>'onplans');
$this->template->write_view('meta', 'html/meta', $Dmeta, true);
$this->template->write_view('header', 'html/header', $Dheader, true);
$this->template->write_view('content', 'onplans/englishset', $DContent,true);
$this->template->write_view('sidebar', 'html/sidebar');
$this->template->write_view('footer', 'html/footer');
$this->template->render();
}
on the destination controller called user
$this->load->helper('url');
$this->load->helper('language');
print_r('lang_session'.$this->session->userdata('lang_name'));
$lang = $this->session->userdata('lang_name');
if(!isset($lang)){ //load default language
$this->lang->load('user');
}else{ //load language from session
print_r('lang :'.$this->session->userdata('lang_name'));
$this->lang->load('user',$this->session->userdata('lang_name')); //);
}
now its working

Passing Two Arrays to View

OK, below is a get_members function in my controller that I pulled and manipulated from the interwebs... i can print out the information from $output in the controller, but I don't want to do that... I cannot figure out how to get it to be part of my view so I can list info from it freely...
I know it has something to do with the $data array in the index function... can anyone assist?
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Phonedirectory extends CI_Controller {
function get_members($group=FALSE,$inclusive=FALSE) {
// Active Directory server
$ldap_host = "fps";
// Active Directory DN
$ldap_dn = "OU=Users,DC=xxx,DC=org";
// User attributes we want to keep
$keep = array(
"samaccountname",
"displayName",
"telephonenumber"
);
// Connect to AD
$ldap = ldap_connect($ldap_host) or die("Could not connect to LDAP");
ldap_set_option ($ldap, LDAP_OPT_REFERRALS, 0);
ldap_set_option($ldap, LDAP_OPT_PROTOCOL_VERSION, 3);
ldap_bind($ldap, "CN=LDAP Reader,OU=Users - Special,DC=xxx,DC=org", "xxx") or die("Could not bind to LDAP");
// Begin building query
if($group) $query = "(&"; else $query = "";
$query .= "(&(objectClass=user)(objectCategory=person))";
// Filter by memberOf, if group is set
if(is_array($group)) {
// Looking for a members amongst multiple groups
if($inclusive) {
// Inclusive - get users that are in any of the groups
// Add OR operator
$query .= "(|";
} else {
// Exclusive - only get users that are in all of the groups
// Add AND operator
$query .= "(&";
}
// Append each group
foreach($group as $g) $query .= "(memberOf=OU=$g,$ldap_dn)";
$query .= ")";
} elseif($group) {
// Just looking for membership of one group
$query .= "(memberOf=OU=$group,$ldap_dn)";
}
// Close query
if($group) $query .= ")"; else $query .= "";
// Uncomment to output queries onto page for debugging
// print_r($query);
// Search AD
$results = ldap_search($ldap,$ldap_dn,$query);
$entries = ldap_get_entries($ldap, $results);
// Remove first entry (it's always blank)
array_shift($entries);
$output = array(); // Declare the output array
$i = 0; // Counter
// Build output array
foreach($entries as $u) {
foreach($keep as $x) {
// Check for attribute
if(isset($u[$x][0])) $attrval = $u[$x][0]; else $attrval = NULL;
// Append attribute to output array
$output[$i][$x] = $attrval;
}
$i++;
}
return $output;
}
public function index() {
$data = array('title' => 'Phone Directory', 'main_content' => 'pages/phoneDirectory');
$this->load->view('template/main', $data);
}
}
Correct me if I'm wrong, but it sounds like you just want the output sent to the view?
If that's the case, then add this to the index function
public function index() {
$data = array('title' => 'Phone Directory', 'main_content' => 'pages/phoneDirectory');
$data['members'] = $this->get_members();
$this->load->view('template/main', $data);
}
or however you want to append that to your data array.
Then in the view you can do:
<?php echo print_r($members, TRUE); ?>

Resources