Update Table without loops - laravel

There is a table foo and it has a column called fooPos. I ned to update the fooPos column with respect to id.
I have the following data
$id = [21,23,34,56,76];
$fooPos = [1,2,3,4,5];
How can I update this without using loops?
It's like 21(id) => 1(fooPos), 23 => 2, 34 =>3 etc.,

You have a solution with INSERT INTO ... ON DUPLICATE KEY UPDATE..., more details in here Multiple update
That solution can trigger an error if the ID doesn't exist and you have some other required fields. In that cas you ca use this solution:
$updateSets = [];
$ids = [21,23,34,56,76];
$fooPos = [1,2,3,4,5];
foreach ($ids as $key => $id) {
$updateSets[] = 'SELECT '.$id.' as set_id, '.$fooPos[$key].' as pos ';
}
$updateSetsString = implode(' UNION ALL ', $updateSets);
\DB::statement('UPDATE your_table JOIN ('.$updateSetsString.') up_set ON your_table.id = up_set.set_id SET your_table.pos = up_set.pos');

function updateTableWithoutQueryLoops()
{
try {
$id = collect([21,23,34,56,76]);
$fooPos = collect([1,2,3,4,5]);
// To check both parameters should have an equal number of elements.
if(count($id) == count($fooPos) ) {
$combinedValues = $id->combine($fooPos);
} else {
return 'Please check equal number of elements for give arrays.';
}
// Run foreach loop of Combined values
foreach ($combinedValues as $id => $fooPos) {
$id = (int) $id;
$cases[] = "WHEN {$id} then ?";
$params[] = $fooPos;
$ids[] = $id;
}
$ids = implode(',', $ids);
$cases = implode(' ', $cases);
$params[] = \Carbon\Carbon::now();
return \DB::update("UPDATE `foo` SET `fooPos` = CASE `id` {$cases} END, `updated_at` = ? WHERE `id` in ({$ids})", $params);
} catch (\Exception $e) {
return 'Exception message:' . $e->getMessage() . ' with code: ' . $e->getCode();
}
}
function updateTableWithoutQueryLoops()
{
try {
$id = collect([21,23,34,56,76]);
$fooPos = collect([1,2,3,4,5]);
// To check both parameters should have an equal number of elements.
if(count($id) == count($fooPos) ) {
$combinedValues = $id->combine($fooPos);
} else {
return 'Please check equal number of elements for give arrays.';
}
// Run foreach loop of Combined values
foreach ($combinedValues as $id => $fooPos) {
$id = (int) $id;
$cases[] = "WHEN {$id} then ?";
$params[] = $fooPos;
$ids[] = $id;
}
$ids = implode(',', $ids);
$cases = implode(' ', $cases);
$params[] = \Carbon\Carbon::now();
return \DB::update("UPDATE `foo` SET `fooPos` = CASE `id` {$cases} END, `updated_at` = ? WHERE `id` in ({$ids})", $params);
} catch (\Exception $e) {
return 'Exception message:' . $e->getMessage() . ' with code: ' . $e->getCode();
}
}

Related

multiple voyager browse blade laravel

i have Product Model and it have bread in voyager and everything is ok.
Products have publisher_id column if null == main else int(id of publisher).
i want create multiple browse blade but one of those is default voyager blade
and another where('publisher_id','!=',null)
to show .
how to created it with route ?
thanks .
fixed with resource route
Route::resource('products/index/publisher', VoyagerProductPublisherController::class);
Route::resource('products/index/notaccept', VoyagerProductPublisherNotAcceptController::class);
and then in controllers index function write query
public function index(Request $request)
{
// GET THE SLUG, ex. 'posts', 'pages', etc.
$slug = \request()->segment(3);
// GET THE DataType based on the slug
$dataType = Voyager::model('DataType')->where('slug', '=', $slug)->first();
// Check permission
$getter = 'paginate';
$search = (object)['value' => $request->get('s'), 'key' => $request->get('key'), 'filter' => $request->get('filter')];
$searchNames = [];
if ($dataType->server_side) {
$searchNames = $dataType->browseRows->mapWithKeys(function ($row) {
return [$row['field'] => $row->getTranslatedAttribute('display_name')];
});
}
$orderBy = $request->get('order_by', $dataType->order_column);
$sortOrder = $request->get('sort_order', $dataType->order_direction);
$usesSoftDeletes = false;
$showSoftDeleted = false;
// Next Get or Paginate the actual content from the MODEL that corresponds to the slug DataType
if (strlen($dataType->model_name) != 0) {
$model = app($dataType->model_name);
$query = $model::select($dataType->name . '.*');
if ($dataType->scope && $dataType->scope != '' && method_exists($model, 'scope' . ucfirst($dataType->scope))) {
$query->{$dataType->scope}();
}
// Use withTrashed() if model uses SoftDeletes and if toggle is selected
if ($model && in_array(SoftDeletes::class, class_uses_recursive($model))) {
$usesSoftDeletes = true;
if ($request->showSoftDeleted && $request->showSoftDeleted == 1) {
$showSoftDeleted = true;
$query = $query->onlyTrashed();
}
}
// If a column has a relationship associated with it, we do not want to show that field
$this->removeRelationshipField($dataType, 'browse');
if ($search->value != '' && $search->key && $search->filter) {
$search_filter = ($search->filter == 'equals') ? '=' : 'LIKE';
$search_value = ($search->filter == 'equals') ? $search->value : '%' . $search->value . '%';
$searchField = $dataType->name . '.' . $search->key;
if ($row = $this->findSearchableRelationshipRow($dataType->rows->where('type', 'relationship'), $search->key)) {
$query->whereIn(
$searchField,
$row->details->model::where($row->details->label, $search_filter, $search_value)->pluck('id')->toArray()
);
} else {
if ($dataType->browseRows->pluck('field')->contains($search->key)) {
$query->where($searchField, $search_filter, $search_value);
}
}
}
$row = $dataType->rows->where('field', $orderBy)->firstWhere('type', 'relationship');
if ($orderBy && (in_array($orderBy, $dataType->fields()) || !empty($row))) {
$querySortOrder = (!empty($sortOrder)) ? $sortOrder : 'desc';
if (!empty($row)) {
$query->select([
$dataType->name . '.*',
'joined.' . $row->details->label . ' as ' . $orderBy,
])->leftJoin(
$row->details->table . ' as joined',
$dataType->name . '.' . $row->details->column,
'joined.' . $row->details->key,
);
}
$dataTypeContent = call_user_func([
$query->orderBy($orderBy, $querySortOrder)->where('publisher_id','!=',null),
$getter,
]);
} elseif ($model->timestamps) {
$dataTypeContent = call_user_func([$query->latest($model::CREATED_AT)->where('publisher_id','!=',null), 'paginate'], request()->perPage ?? 10);
} else {
$dataTypeContent = call_user_func([$query->orderBy($model->getKeyName(), 'DESC')->where('publisher_id','!=',null), $getter]);
}
// Replace relationships' keys for labels and create READ links if a slug is provided.
$dataTypeContent = $this->resolveRelations($dataTypeContent, $dataType);
} else {
// If Model doesn't exist, get data from table name
$dataTypeContent = call_user_func([DB::table($dataType->name)->where('publisher_id','!=',null), $getter]);
$model = false;
}
// Check if BREAD is Translatable
$isModelTranslatable = is_bread_translatable($model);
// Eagerload Relations
$this->eagerLoadRelations($dataTypeContent, $dataType, 'browse', $isModelTranslatable);
// Check if server side pagination is enabled
$isServerSide = isset($dataType->server_side) && $dataType->server_side;
// Check if a default search key is set
$defaultSearchKey = $dataType->default_search_key ?? null;
// Actions
$actions = [];
if (!empty($dataTypeContent->first())) {
foreach (Voyager::actions() as $action) {
$action = new $action($dataType, $dataTypeContent->first());
if ($action->shouldActionDisplayOnDataType()) {
$actions[] = $action;
}
}
}
//Define showCheckboxColumn
$showCheckboxColumn = false;
if (Auth::guard('admin')->user()->can('delete', app($dataType->model_name))) {
$showCheckboxColumn = true;
} else {
foreach ($actions as $action) {
if (method_exists($action, 'massAction')) {
$showCheckboxColumn = true;
}
}
}
// Define orderColumn
$orderColumn = [];
if ($orderBy) {
$index = $dataType->browseRows->where('field', $orderBy)->keys()->first() + ($showCheckboxColumn ? 1 : 0);
$orderColumn = [[$index, $sortOrder ?? 'desc']];
}
// Define list of columns that can be sorted server side
$sortableColumns = $this->getSortableColumns($dataType->browseRows);
$view = 'voyager::bread.publisher';
if (view()->exists("voyager::$slug.publisher")) {
$view = "voyager::$slug.publisher";
}
return Voyager::view($view, compact(
'actions',
'dataType',
'dataTypeContent',
'isModelTranslatable',
'search',
'orderBy',
'orderColumn',
'sortableColumns',
'sortOrder',
'searchNames',
'isServerSide',
'defaultSearchKey',
'usesSoftDeletes',
'showSoftDeleted',
'showCheckboxColumn'
));
}
// in controller two
public function index(Request $request)
{
// GET THE SLUG, ex. 'posts', 'pages', etc.
$slug = \request()->segment(3);
// GET THE DataType based on the slug
$dataType = Voyager::model('DataType')->where('slug', '=', $slug)->first();
// Check permission
$getter = 'paginate';
$search = (object)['value' => $request->get('s'), 'key' => $request->get('key'), 'filter' => $request->get('filter')];
$searchNames = [];
if ($dataType->server_side) {
$searchNames = $dataType->browseRows->mapWithKeys(function ($row) {
return [$row['field'] => $row->getTranslatedAttribute('display_name')];
});
}
$orderBy = $request->get('order_by', $dataType->order_column);
$sortOrder = $request->get('sort_order', $dataType->order_direction);
$usesSoftDeletes = false;
$showSoftDeleted = false;
// Next Get or Paginate the actual content from the MODEL that corresponds to the slug DataType
if (strlen($dataType->model_name) != 0) {
$model = app($dataType->model_name);
$query = $model::select($dataType->name . '.*');
if ($dataType->scope && $dataType->scope != '' && method_exists($model, 'scope' . ucfirst($dataType->scope))) {
$query->{$dataType->scope}();
}
// Use withTrashed() if model uses SoftDeletes and if toggle is selected
if ($model && in_array(SoftDeletes::class, class_uses_recursive($model))) {
$usesSoftDeletes = true;
if ($request->showSoftDeleted && $request->showSoftDeleted == 1) {
$showSoftDeleted = true;
$query = $query->onlyTrashed();
}
}
// If a column has a relationship associated with it, we do not want to show that field
$this->removeRelationshipField($dataType, 'browse');
if ($search->value != '' && $search->key && $search->filter) {
$search_filter = ($search->filter == 'equals') ? '=' : 'LIKE';
$search_value = ($search->filter == 'equals') ? $search->value : '%' . $search->value . '%';
$searchField = $dataType->name . '.' . $search->key;
if ($row = $this->findSearchableRelationshipRow($dataType->rows->where('type', 'relationship'), $search->key)) {
$query->whereIn(
$searchField,
$row->details->model::where($row->details->label, $search_filter, $search_value)->pluck('id')->toArray()
);
} else {
if ($dataType->browseRows->pluck('field')->contains($search->key)) {
$query->where($searchField, $search_filter, $search_value);
}
}
}
$row = $dataType->rows->where('field', $orderBy)->firstWhere('type', 'relationship');
if ($orderBy && (in_array($orderBy, $dataType->fields()) || !empty($row))) {
$querySortOrder = (!empty($sortOrder)) ? $sortOrder : 'desc';
if (!empty($row)) {
$query->select([
$dataType->name . '.*',
'joined.' . $row->details->label . ' as ' . $orderBy,
])->leftJoin(
$row->details->table . ' as joined',
$dataType->name . '.' . $row->details->column,
'joined.' . $row->details->key,
);
}
$dataTypeContent = call_user_func([
$query->orderBy($orderBy, $querySortOrder)->where('accept',0),
$getter,
]);
} elseif ($model->timestamps) {
$dataTypeContent = call_user_func([$query->latest($model::CREATED_AT)->where('accept',0), 'paginate'], request()->perPage ?? 10);
} else {
$dataTypeContent = call_user_func([$query->orderBy($model->getKeyName(), 'DESC')->where('accept',0), $getter]);
}
// Replace relationships' keys for labels and create READ links if a slug is provided.
$dataTypeContent = $this->resolveRelations($dataTypeContent, $dataType);
} else {
// If Model doesn't exist, get data from table name
$dataTypeContent = call_user_func([DB::table($dataType->name)->where('accept',0), $getter]);
$model = false;
}
// Check if BREAD is Translatable
$isModelTranslatable = is_bread_translatable($model);
// Eagerload Relations
$this->eagerLoadRelations($dataTypeContent, $dataType, 'browse', $isModelTranslatable);
// Check if server side pagination is enabled
$isServerSide = isset($dataType->server_side) && $dataType->server_side;
// Check if a default search key is set
$defaultSearchKey = $dataType->default_search_key ?? null;
// Actions
$actions = [];
if (!empty($dataTypeContent->first())) {
foreach (Voyager::actions() as $action) {
$action = new $action($dataType, $dataTypeContent->first());
if ($action->shouldActionDisplayOnDataType()) {
$actions[] = $action;
}
}
}
//Define showCheckboxColumn
$showCheckboxColumn = false;
if (Auth::guard('admin')->user()->can('delete', app($dataType->model_name))) {
$showCheckboxColumn = true;
} else {
foreach ($actions as $action) {
if (method_exists($action, 'massAction')) {
$showCheckboxColumn = true;
}
}
}
// Define orderColumn
$orderColumn = [];
if ($orderBy) {
$index = $dataType->browseRows->where('field', $orderBy)->keys()->first() + ($showCheckboxColumn ? 1 : 0);
$orderColumn = [[$index, $sortOrder ?? 'desc']];
}
// Define list of columns that can be sorted server side
$sortableColumns = $this->getSortableColumns($dataType->browseRows);
$view = 'voyager::bread.notaccept';
if (view()->exists("voyager::$slug.notaccept")) {
$view = "voyager::$slug.notaccept";
}
return Voyager::view($view, compact(
'actions',
'dataType',
'dataTypeContent',
'isModelTranslatable',
'search',
'orderBy',
'orderColumn',
'sortableColumns',
'sortOrder',
'searchNames',
'isServerSide',
'defaultSearchKey',
'usesSoftDeletes',
'showSoftDeleted',
'showCheckboxColumn'
));
}
thanks for view .

Laravel chunk filter collection

Actually i have a simple collection but i need to make a filter to this collection and the filter call GoogleMaps to determine the distance between origin and destination, the problem is that i have more than 100 row $arbitres and this part of the process is getting very very very long.
How could i do to get more performance ?
I would like to try chunk but a get
Method newQuery does not exist.
`
here my method to get the collection :
$arbitres = Licencies::getArbitres($rencontre->dt_rencontre);
public static function getArbitres($date){
$licences = Licencies::whereIn('activite_licencie_id' , [24,25,50,80])
->where('valid_licence_id' , 3)
->where('saison_id' , self::getSaison()->id)
->where('dispo' , 1)
->whereHas('fonctions')
->whereHas('divisions')
->whereDoesntHave('rencontreOfficiels', function ($query) use ($date) {
$query->where('dt_rencontre', $date);
})->get();
return $licences;
}
here my process who is getting so long : ('m doing this in order to filter $arbitres with the shortest distance.
for($i=0; $i <= 1200 ; $i+=200){
$geo_filter = $arbitres->filter(function ($arbitre) use ($rencontre , $i) {
$origin = $arbitre->lb_adresse .' '. $arbitre->lb_ville_naissance .' '. $arbitre->cd_dept_naissance;
$destination = $rencontre->stade->adresse_stade .' '. $rencontre->stade->ville_stade .' '. $rencontre->stade->cd_post_stade;
$distance = getDistance($origin, $destination);
$distance = (float)$distance;
if($distance <= $i){
return true;
}
return false;
});
if ($geo_filter->isNotEmpty()) {
$arbitres = $geo_filter;
break;
}
}
fonction getdistance :
function getDistance($origin, $destination){
$distance = 0;
$response = \GoogleMaps::load('directions')
->setParam([
'origin' => $origin,
'destination' => $destination,
'mode' => 'driving' ,
'language' => 'fr',
])->get();
$parsed_json = (json_decode($response));
if($parsed_json->status != "NOT_FOUND") {
$result = $parsed_json->{'routes'}[0]->{'legs'}[0]->{'distance'}->{'text'};
$a = $result;
$b = str_replace(" km",'',$a);
$distance = str_replace(",",'.',$b);
}
if(is_numeric($distance)){
$distance = $distance * 2;
}
return $distance;
}

CodeIgniter - get row from table where id is id of array

I have one table korisnik with 3 columns (id, username, password).
I want some like:
$upit = "SELECT * FROM korisnik WHERE username = '" . $_POST['username'] . "'
AND password = SHA1('" . $_POST['password'] . "')";
$temp = $upit->fetch(PDO::FETCH_ASSOC);
$_SESSION['id'] = $temp['id'];
if ($pdo_izraz->num_rows() == 1) {
session_start();
$_SESSION['autorizovan'] = 1;
$temp = $pdo_izraz->fetch(PDO::FETCH_ASSOC);
$_SESSION['id'] = $temp['id'];
$upit = ("Select * from korisnici where id=" . $_SESSION['id']);*
$izraz = $dbh->query($upit);
$obj = $izraz->fetch(PDO::FETCH_ASSOC);
$username = $obj['username'];
echo "<p id='bbb'><b >$username</b>:Welcome</p>";
I want to do something like this in CodeIgniter (to get one row where id=array of one row ($_SESSION['id']
I think you are looking for result_array()
see the manual here
$query = $this->db->query("YOUR QUERY");
foreach ($query->result_array() as $row)
{
echo $row['title'];
echo $row['name'];
echo $row['body'];
}
UPDATE
public function login($user, $pass) // Takeing the username/pass from form
{
$this->db->where('username', $user);
$this->db->where('password', md5($pass));
$query = $this->db->get('korisnici');
if ($query->num_rows() == 1)
{
$_SESSION['id'] = $this->query->row()->id;
return TRUE;
}
else
{
return FALSE;
}
}
public function getData()//Get result of array
{
$this->db->where('id', $_SESSION['id']);
$query = $this->db->get('korisnici');
return $query->result(); // here you can change for result_array() if you want
}

Multiselection in Layered navigation In Magento

In layered navigation, when i select particular attribute, it gets disappeared from left side selection panel, so I want I should be able to select more than once.
If I come to know from what collection it is coming, that will be helpful.
-Thanks in Advance.
public function apply(Zend_Controller_Request_Abstract $request, $filterBlock) {
$filter = $request->getParam($this->_requestVar);
if (is_array($filter)) {
$text = array();
foreach ($filter as $f)
array_push ($text, $this->_getOptionText($f));
if ($filter && $text) {
$this->_getResource()->applyFilterToCollection($this, $filter);
$this->getLayer()->getState()->addFilter($this->_createItem($text, $filter));
$this->_items = array();
}
return $this;
}
$text = $this->_getOptionText($filter);
if ($filter && $text) {
$this->_getResource()->applyFilterToCollection($this, $filter);
$this->getLayer()->getState()->addFilter($this->_createItem($text, $filter));
$this->_items = array();
}
return $this;
}
public function applyFilterToCollection($filter, $value)
{
$collection = $filter->getLayer()->getProductCollection();
$attribute = $filter->getAttributeModel();
$connection = $this->_getReadAdapter();
$tableAlias = $attribute->getAttributeCode() . '_idx';
if (!is_array($value)) {
$conditions = array(
"{$tableAlias}.entity_id = e.entity_id",
$connection->quoteInto("{$tableAlias}.attribute_id = ?", $attribute->getAttributeId()),
$connection->quoteInto("{$tableAlias}.store_id = ?", $collection->getStoreId()),
$connection->quoteInto("{$tableAlias}.value = ?", $value)
);
}else{
$conditions = array(
"{$tableAlias}.entity_id = e.entity_id",
$connection->quoteInto("{$tableAlias}.attribute_id = ?", $attribute->getAttributeId()),
$connection->quoteInto("{$tableAlias}.store_id = ?", $collection->getStoreId()),
$connection->quoteInto("{$tableAlias}.value in (?)",$value)
);
}
$collection->getSelect()->join(
array($tableAlias => $this->getMainTable()),
implode(' AND ', $conditions),
array()
);
//echo $collection->getSelect();
return $this;
}
I've done something similar, and you have to rewrite the Mage_Catalog_Model_Layer_Filter_Attribute class, which uses the method apply() to filter results.

how to use this simple acl library into codeigniter

i used cakephp before and now use codeigniter but Unfortunately hasn't any authentication or ACL built-in library ..after more search i have found a good library, but I do not know how to use it..it is no example to use it..any one have create controller and model as sample...thanks for helping
<?php
(defined('BASEPATH')) OR exit('No direct script access allowed');
class acl {
/* Actions::::
* Create 1
* Read 2
* Update 4
* Delete 8
* The allowance is made by a sum of the actions allowed.
* Ex.: user can read and update (2+4)=6 … so ill put 6 instead of 1 or 0.
*
* if(!$this->acl->hasPermission(‘entries_complete_access')) {
echo “No no”;
} else
* echo “yeah”;
}
*
*
*/
var $perms = array(); //Array : Stores the permissions for the user
var $userID; //Integer : Stores the ID of the current user
var $userRoles = array(); //Array : Stores the roles of the current user
var $ci;
function __construct($config = array()) {
$this->ci = &get_instance();
$this->userID = floatval($this->ci->session->userdata('account_id'));
$this->userRoles = $this->getUserRoles();
$this->buildACL();
}
function buildACL() {
//first, get the rules for the user's role
if (count($this->userRoles) > 0) {
$this->perms = array_merge($this->perms, $this->getRolePerms($this->userRoles));
}
//then, get the individual user permissions
$this->perms = array_merge($this->perms, $this->getUserPerms($this->userID));
}
function getPermKeyFromID($permID) {
//$strSQL = “SELECT `permKey` FROM `”.DB_PREFIX.”permissions` WHERE `ID` = ” . floatval($permID) . ” LIMIT 1″;
$this->ci->db->select('permKey');
$this->ci->db->where('id', floatval($permID));
$sql = $this->ci->db->get('perm_data', 1);
$data = $sql->result();
return $data[0]->permKey;
}
function getPermNameFromID($permID) {
//$strSQL = “SELECT `permName` FROM `”.DB_PREFIX.”permissions` WHERE `ID` = ” . floatval($permID) . ” LIMIT 1″;
$this->ci->db->select('permName');
$this->ci->db->where('id', floatval($permID));
$sql = $this->ci->db->get('perm_data', 1);
$data = $sql->result();
return $data[0]->permName;
}
function getRoleNameFromID($roleID) {
//$strSQL = “SELECT `roleName` FROM `”.DB_PREFIX.”roles` WHERE `ID` = ” . floatval($roleID) . ” LIMIT 1″;
$this->ci->db->select('roleName');
$this->ci->db->where('id', floatval($roleID), 1);
$sql = $this->ci->db->get('role_data');
$data = $sql->result();
return $data[0]->roleName;
}
function getUserRoles() {
//$strSQL = “SELECT * FROM `”.DB_PREFIX.”user_roles` WHERE `userID` = ” . floatval($this->userID) . ” ORDER BY `addDate` ASC”;
$this->ci->db->where(array('userID' => floatval($this->userID)));
$this->ci->db->order_by('addDate', 'asc');
$sql = $this->ci->db->get('user_roles');
$data = $sql->result();
$resp = array();
foreach ($data as $row) {
$resp[] = $row->roleID;
}
return $resp;
}
function getAllRoles($format = 'ids') {
$format = strtolower($format);
//$strSQL = “SELECT * FROM `”.DB_PREFIX.”roles` ORDER BY `roleName` ASC”;
$this->ci->db->order_by('roleName', 'asc');
$sql = $this->ci->db->get('role_data');
$data = $sql->result();
$resp = array();
foreach ($data as $row) {
if ($format == 'full') {
$resp[] = array('id' => $row->ID, 'name' => $row->roleName);
} else {
$resp[] = $row->ID;
}
}
return $resp;
}
function getAllPerms($format = 'ids') {
$format = strtolower($format);
//$strSQL = “SELECT * FROM `”.DB_PREFIX.”permissions` ORDER BY `permKey` ASC”;
$this->ci->db->order_by('permKey', 'asc');
$sql = $this->ci->db->get('perm_data');
$data = $sql->result();
$resp = array();
foreach ($data as $row) {
if ($format == 'full') {
$resp[$row->permKey] = array('id' => $row->ID, 'name' => $row->permName, 'key' => $row->permKey);
} else {
$resp[] = $row->ID;
}
}
return $resp;
}
function getRolePerms($role) {
if (is_array($role)) {
//$roleSQL = “SELECT * FROM `”.DB_PREFIX.”role_perms` WHERE `roleID` IN (” . implode(“,”,$role) . “) ORDER BY `ID` ASC”;
$this->ci->db->where_in('roleID', $role);
} else {
//$roleSQL = “SELECT * FROM `”.DB_PREFIX.”role_perms` WHERE `roleID` = ” . floatval($role) . ” ORDER BY `ID` ASC”;
$this->ci->db->where(array('roleID' => floatval($role)));
}
$this->ci->db->order_by('id', 'asc');
$sql = $this->ci->db->get('role_perms'); //$this->db->select($roleSQL);
$data = $sql->result();
$perms = array();
foreach ($data as $row) {
$pK = strtolower($this->getPermKeyFromID($row->permID));
if ($pK == '') {
continue;
}
/* if ($row->value == '1′) {
$hP = true;
} else {
$hP = false;
} */
if ($row->value == '0') {
$hP = false;
} else {
$hP = $row->value;
}
$perms[$pK] = array('perm' => $pK, '1inheritted' => true, 'value' => $hP, 'name' => $this->getPermNameFromID($row->permID), 'id' => $row->permID);
}
return $perms;
}
function getUserPerms($userID) {
//$strSQL = “SELECT * FROM `”.DB_PREFIX.”user_perms` WHERE `userID` = ” . floatval($userID) . ” ORDER BY `addDate` ASC”;
$this->ci->db->where('userID', floatval($userID));
$this->ci->db->order_by('addDate', 'asc');
$sql = $this->ci->db->get('user_perms');
$data = $sql->result();
$perms = array();
foreach ($data as $row) {
$pK = strtolower($this->getPermKeyFromID($row->permID));
if ($pK == '') {
continue;
}
/* if ($row->value == '1′) {
$hP = true;
} else {
$hP = false;
} */
if ($row->value == '0') {
$hP = false;
} else {
$hP = $row->value;
}
$perms[$pK] = array('perm' => $pK, '2inheritted' => false, 'value' => $hP, 'name' => $this->getPermNameFromID($row->permID), 'id' => $row->permID);
}
return $perms;
}
function hasRole($roleID) {
foreach ($this->userRoles as $k => $v) {
if (floatval($v) === floatval($roleID)) {
return true;
}
}
return false;
}
function actionPerm($value, $wanted) {
/* Actions::::
* Create 1
* Read, 2
* Update, 4
* Delete 8
*/
$action['create'] = array('1', '3', '5', '9', '11', '13', '15'); //1
$action['read'] = array('2', '3', '6', '10', '14', '15'); //2
$action['update'] = array('4', '5', '6', '7', '12', '13', '14', '15'); //4
$action['delete'] = array('8', '9', '10', '11', '12', '13', '14', '15'); //8
$action['all'] = array('15');
if (in_array($value, $action[$wanted], true)) {
return true;
} else {
return false;
}
}
function hasPermission($permKey, $action = 'all') {
$permKey = strtolower($permKey);
if (array_key_exists($permKey, $this->perms)) {
if ($this->actionPerm($this->perms[$permKey]['value'], $action)) {
return true;
} else {
return false;
}
} else {
return false;
}
/* OLD METHOD
if ($this->perms[$permKey]['value'] === '1′ || $this->perms[$permKey]['value'] === true)
{
return true;
} else {
return false;
}
} else {
return false;
}
*/
}
}
and this is the url
sample ACL Class for codeigniter
This is simple
Load it first in your controller
$this->load->library('acl');
Now call its method
$this->acl->buildACL();
EDIT
Use these for menuall assigning
$this->acl->perms = array('your values');
$this->acl->userID= 'user id';
$this->acl->userRoles = array('your values');
Note that you should have db table userRoles which will be invoked when the library is initialized getUserRoles method will be called and $userRoles parameter will have values.
I'm Brian from Tastybytes. My best solution would be to step through the tutorial that the code igniter ACL library is based on. It is a 100% straight port from the base php files to CI Library.
http://net.tutsplus.com/tutorials/php/a-better-login-system/
And possibly look at the very bottom of the page where I go through "Installation" and what not.

Resources