I'm new with Codeigniter. I got error on my code using Codeigniter. My index doesn't show the row of my datatable, even my datatable had data in it. Anyone can find my error or typo text on my code? Please help me :(.
btw I have 2 controllers.
Here's my first controller (modules->api->controller->Tower.php)
defined('BASEPATH') OR exit('No direct script access allowed');
require_once APPPATH . '/core/MY_Auth.php';
require 'vendor/autoload.php';
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
class Tower extends MY_Auth
{
protected $ruleMsg;
function __construct()
{
parent::__construct();
$this->load->model('Model_tower');
$this->load->library('Pagingmeta');
$this->load->library('Validate');
$this->ruleMsg = '%s must be filled';
}
public function index_get($id = '') {
if (!empty($id)) {
return $this->get_detail($id);
}
$keyword = $this->get('search', true);
$except = $this->get('excepth', true);
$type = $this->get('type', true)??'list';
$page = $this->get('page', true)??1;
$limit = $this->get('limit', true)??10;
$data = $this->Model_tower->get_list($keyword, $this->role, $this->regional, $page, $limit);
$this->response([
'message' => 'Get tower success',
'data' => $data['data'],
'meta' => $this->pagingmeta->get_meta($data['total'], $limit, $page)
], REST_Controller::HTTP_OK);
}
private function get_detail($id) {
$data = $this->Model_tower->get_detail($id);
if (empty($data)) {
return $this->response([
'message' => 'Data not found'
], REST_Controller::HTTP_BAD_REQUEST);
}
if ($this->regional != $data->regional && $this->role != 'ADMN' && $id != $this->userId) {
return $this->response([
'message' => "You didn't have right to access this data"
], REST_Controller::HTTP_BAD_REQUEST);
}
if ($this->role == 'ADMN') {
$data->is_editable = true;
}
return $this->response([
'message' => 'Get tower success',
'data' => $data
], REST_Controller::HTTP_OK);
}
public function tower_post() {
$this->validate_role();
$rules = $this->rules_post($this->post(null, true));
$params = $this->validate->validation($this->post(null, true), $rules);
if (!$params['status']) {
$this->response([
'message' => $params['errors'][0]
], REST_Controller::HTTP_BAD_REQUEST);
}
$params = $params['data'];
if ($this->Model_tower->validate_site_id($params['site_id'])) {
$this->response([
'message' => 'Site ID already exist'
], REST_Controller::HTTP_BAD_REQUEST);
}
$id = $this->Model_tower->tower_action($params, $this->userId);
$this->response([
'message' => 'Create tower success',
'data' => $id
], REST_Controller::HTTP_CREATED);
}
public function tower_put($id = '') {
$this->validate_role();
$rules = $this->rules_post($this->put(null, true));
$params = $this->validate->validation($this->put(null, true), $rules);
if (!$params['status']) {
$this->response([
'message' => $params['errors'][0]
], REST_Controller::HTTP_BAD_REQUEST);
}
$params = $params['data'];
if ($this->Model_tower->validate_site_id($params['site_id'], $id)) {
$this->response([
'message' => 'Site ID already exist'
], REST_Controller::HTTP_BAD_REQUEST);
}
$this->Model_tower->tower_action($params, $this->userId, $id);
$this->response([
'message' => 'Update tower success',
'data' => $id
], REST_Controller::HTTP_OK);
}
public function upload_post() {
$this->validate_role();
$this->load->library('Uuid');
$spreadsheet = \PhpOffice\PhpSpreadsheet\IOFactory::load($_FILES['data']['tmp_name']);
$sheet = $spreadsheet->getActiveSheet();
// Store data from the activeSheet to the varibale in the form of Array
$data = array_values($sheet->toArray(null,true,true,true));
$oldData = $this->Model_tower->get_all_data();
$oldData = array_column($oldData, 'site_id');
$insertData = [];
$now = date('Y-m-d H:i:s');
foreach($data as $index => $d) {
if ($index == 0) {
continue;
}
$code = $this->uuid->generate();
$type = '';
$regional = '';
$inputedType = $d['D'];
if ($inputedType == 'MTEL') {
$type = 'mtel';
} else {
$type = 'reseller';
}
$inputedRegional = $d['G'];
if ($inputedRegional == 'Jawa Timur') {
$regional = 'JATIM';
} else if ($inputedRegional == 'Jawa Tengah') {
$regional = 'JATENG';
} else {
$regional = 'BALNUS';
}
if (empty($d['A']) || empty($d['B']) || in_array($d['A'], $oldData)) {
break;
}
$insertData[] = [
'site_id' => $d['A'],
'project_id' => $d['B'],
'site_name' => $d['C'],
'type' => $type,
'company' => $d['E'],
'address' => $d['F'],
'regional_code' => $regional,
'active_status' => 1,
'created_at' => $now,
'updated_at' => $now,
'code' => $code,
'created_by' => $this->userId,
'updated_by' => $this->userId
];
}
if (!empty($insertData)) {
$this->Model_tower->insert_batch($insertData);
}
$this->response([
'message' => 'Bulk insert success',
], REST_Controller::HTTP_CREATED);
}
private function validate_role() {
if ($this->role != 'ADMN') {
return $this->response([
'message' => "You didn't have right to access this action"
], REST_Controller::HTTP_BAD_REQUEST);
}
}
private function rules_post() {
return [
[
'field' => 'site_id',
'label' => 'Site id',
'rules' => 'required',
'errors' => ['required' => $this->ruleMsg]
],
[
'field' => 'project_id',
'label' => 'Project id',
'rules' => 'required',
'errors' => ['required' => $this->ruleMsg]
],
[
'field' => 'name',
'label' => 'Name',
'rules' => 'required',
'errors' => ['required' => $this->ruleMsg]
],
[
'field' => 'type',
'label' => 'Type',
'rules' => 'required',
'errors' => ['required' => $this->ruleMsg]
],
[
'field' => 'regional',
'label' => 'Regional',
'rules' => 'required',
'errors' => ['required' => $this->ruleMsg]
],
[
'field' => 'address',
'label' => 'Address',
'rules' => 'required',
'errors' => ['required' => $this->ruleMsg]
],
[
'field' => 'company',
'label' => 'Company',
'rules' => 'required',
'errors' => ['required' => $this->ruleMsg]
],
[
'field' => 'status',
'label' => 'Status',
'rules' => 'required',
'errors' => ['required' => $this->ruleMsg]
],
];
}
}
and this is my second Controller (Controllers->Tower.php)
defined('BASEPATH') OR exit('No direct script access allowed');
require_once APPPATH . '/core/MY_Cont.php';
class Tower extends MY_Cont
{
public function __construct()
{
parent::__construct();
}
public function index() {
$opts = array(
'content_only' => false,
'parent_menu' => 'tower',
'child_menu' => 'List Tower',
'nav_target' => 'tower_list',
);
$this->view('tower/index', $opts);
}
public function detail($code = null) {
if (empty($code)) {
$this->render_invalid();
}
$fetch_detail = $this->get_data_tower($code);
if ($fetch_detail['code'] !== 200) {
$this->render_invalid();
}
$opts = array(
'content_only' => false,
'parent_menu' => 'tower',
'child_menu' => 'Tower Detail',
'tower' => $fetch_detail['response']->data,
'nav_target' => 'tower_list',
);
$this->view('tower/detail', $opts);
}
public function new() {
$regional = $this->get_regional();
$opts = array(
'content_only' => false,
'parent_menu' => 'tower',
'child_menu' => 'Add New Tower',
'list_region' => $regional['response']->data,
'nav_target' => 'tower_new',
);
$this->view('tower/new', $opts);
}
public function bulk() {
$opts = array(
'content_only' => false,
'parent_menu' => 'tower',
'child_menu' => 'Upload Tower',
'nav_target' => 'tower_bulk',
);
$this->view('tower/bulk', $opts);
}
public function edit($code = null) {
if (empty($code)) {
$this->render_invalid();
}
$fetch_detail = $this->get_data_tower($code);
if ($fetch_detail['code'] !== 200) {
$this->render_invalid();
}
$regional = $this->get_regional();
$opts = array(
'content_only' => false,
'parent_menu' => 'tower',
'child_menu' => 'Edit Tower Detail',
'tower' => $fetch_detail['response']->data,
'list_region' => $regional['response']->data,
'nav_target' => 'tower_list',
);
$this->view('tower/edit', $opts);
}
private function render_invalid() {
header('HTTP/1.0 404');
$opts = array(
'content_only' => true,
'cfg_mainclass' => 'fullpage',
'private_routing' => false,
);
$this->view('layouts/404', $opts);
exit();
}
private function get_data_tower($id = '') {
if (empty($id)) {
$curl = curl_init(base_url() . 'api/tower');
} else {
$curl = curl_init(base_url() . 'api/tower/' . $id);
}
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_HTTPHEADER, array(
'Authorization: ' . $this->session->userdata('usertoken'),
));
$result = json_decode(curl_exec($curl));
$httpcode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
curl_close($curl);
return array(
'code' => $httpcode,
'response' => $result,
);
}
private function get_regional() {
$curl = curl_init(base_url() . 'api/master/regional');
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_HTTPHEADER, array(
'Authorization: ' . $this->session->userdata('usertoken'),
));
$result = json_decode(curl_exec($curl));
$httpcode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
curl_close($curl);
$response = array(
'code' => $httpcode,
'response' => $result,
);
return $response;
}
}
and this is my index.php
<div class="container-fluid">
<div class="row">
<div class="col-12">
<div class="mainpanel">
<div class="mainpanel-header">
<div class="row align-items-end">
<div class="col-9">
<h3>List Tower</h3>
<h5>Click on tower to view detail</h5>
</div>
<div class="col text-right">
<a href="{{ base_url }}tower/new" class="panel-cta">
Add new tower
</a>
</div>
</div>
</div>
<form method="post" action="" id="form-filter-data" autocomplete="off">
<div class="digi-tablefilter">
<div class="filter-inputholder">
<label>Search</label>
<input type="text" name="search" placeholder="Search keyword" id="filter-search" />
</div>
<div class="filter-inputholder">
<input type="submit" value="Apply filter" />
</div>
</div>
</form>
<span class="table-information" id="t-info"></span>
<div class="digi-tableholder">
<table>
<thead>
<tr>
<th>Name</th>
<th>Project ID</th>
<th>Site ID</th>
<th>Regional</th>
<th>Company</th>
</tr>
</thead>
<tbody id="tower-table-value"></tbody>
</table>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col">
<div id="test-pag"></div>
</div>
</div>
</div>
</section>
<script>
$(document).ready(function() {
const payload = {
page: 1,
limit: 10,
search: '',
}
fetchListData(payload);
});
function fetchListData(payload) {
var apiURL = "{{ api_server ~ 'tower' }}";
var userToken = getUserToken();
$.ajax({
url: apiURL,
type: "GET",
data: payload,
headers: {
Authorization: userToken,
},
success: function(response) {
const { data, message, meta } = response;
buildDataTable(data, meta);
},
error: function(response) {
const { responseJSON } = response;
addNotification({
type: 'error',
title: 'Fetching data tower gagal',
message: responseJSON.message,
});
return;
}
});
}
function buildDataTable(data, metadata) {
const target = document.getElementById("tower-table-value");
const txtResult = document.getElementById("t-info");
$("#tower-table-value").empty();
target.innerHTML = "";
txtResult.innerHTML = "";
if (data.length == 0) {
buildEmptyRows();
return;
}
$.each(data, function(idx, item) {
const { id, name, project_id, site_id, regional, company } = item;
const tr = document.createElement('tr');
const nameHolder = document.createElement('td');
const projectHolder = document.createElement('td');
const siteHolder = document.createElement('td');
const regionalHolder = document.createElement('td');
const companyHolder = document.createElement('td');
nameHolder.innerHTML = name;
projectHolder.innerHTML = project_id;
siteHolder.innerHTML = site_id;
regionalHolder.innerHTML = regional;
companyHolder.innerHTML = company;
tr.appendChild(nameHolder);
tr.appendChild(projectHolder);
tr.appendChild(siteHolder);
tr.appendChild(regionalHolder);
tr.appendChild(companyHolder);
tr.onclick = function(e) {
window.location.href = `{{ base_url }}tower/detail/${item.id}`;
}
target.appendChild(tr);
});
var $resultText = `Showing result with keyword <strong>${$("#filter-search").val() == '' ? '-' : $("#filter-search").val()}</strong> ${metadata.total} row(s) found.`;
txtResult.innerHTML = $resultText;
if (metadata.last_page > 1) {
buildPagination(metadata);
} else {
hideLoader();
}
}
function buildEmptyRows() {
const target = document.getElementById("tower-table-value");
const txtResult = document.getElementById("t-info");
var $resultText = `Showing result with keyword <strong>${$("#filter-search").val() == '' ? '-' : $("#filter-search").val()}</strong> • 0 row(s) found.`;
txtResult.innerHTML = $resultText;
const tr = document.createElement('tr');
const td = document.createElement('td');
td.colspan = 5;
td.innerHTML = 'No Rows Found.';
tr.appendChild(td);
target.appendChild(tr);
hideLoader();
}
function buildPagination(metadata) {
const { from, to, last_page, current_page, per_page, total } = metadata;
$("#test-pag").pagination({
items: total,
itemsOnPage: per_page,
currentPage: current_page,
onPageClick: function(pageNumber, event) {
event.preventDefault();
const payload = {
page: pageNumber,
limit: per_page,
search: '',
}
fetchListData(payload);
}
});
}
$("#form-filter-data").submit(function(e) {
e.preventDefault();
const $payload = {
page: 1,
limit: 10,
search: $("#filter-search").val()
}
fetchListData($payload);
})
</script>
I'll very thankful if u can solve my problem :D
Related
I'm using Laravel i need to do update stock after order placed from a client/user app i used Http api for that but when i added stock update code in Http api file i'm getting internal server error in user app and also order is no placing if i remove stock update code from Http api it is taking order without error and stock update and the error i'm getting live.ERROR: Undefined variable: total_stock {"userId":1,"exception":"[object] (ErrorException(code: 0): Undefined variable: total_stock at /home/ttrr/domain/folder/app/Http/Controllers/Api/V1/OrderController.php:280) [stacktrace]
Here is my stock update code
$type = $c['variation'][0]['type'];
$var_store = [];
foreach (json_decode($product['variations'], true) as $var) {
if ($type == $var['type']) {
$var['stock'] -= $c['quantity'];
}
array_push($var_store, $var);
}
Product::where(['id' => $product['id']])->update([
'variations' => json_encode($var_store),
'total_stock' => $product['total_stock'] - $c['quantity'],
]);
Here is my ordercontroll.php
class OrderController extends Controller
{
public function track_order(Request $request)
{
$validator = Validator::make($request->all(), [
'order_id' => 'required'
]);
if ($validator->fails()) {
return response()->json(['errors' => Helpers::error_processor($validator)], 403);
}
$order = Order::with(['restaurant', 'delivery_man.rating'])->withCount('details')->where(['id' => $request['order_id'], 'user_id' => $request->user()->id])->first();
if($order)
{
$order['restaurant'] = $order['restaurant']?Helpers::restaurant_data_formatting($order['restaurant']):$order['restaurant'];
$order['delivery_address'] = $order['delivery_address']?json_decode($order['delivery_address']):$order['delivery_address'];
$order['delivery_man'] = $order['delivery_man']?Helpers::deliverymen_data_formatting([$order['delivery_man']]):$order['delivery_man'];
unset($order['details']);
}
else
{
return response()->json([
'errors' => [
['code' => 'schedule_at', 'message' => trans('messages.not_found')]
]
], 404);
}
return response()->json($order, 200);
}
public function place_order(Request $request)
{
$validator = Validator::make($request->all(), [
'order_amount' => 'required',
'payment_method'=>'required|in:cash_on_delivery,digital_payment',
'order_type' => 'required|in:take_away,delivery',
'restaurant_id' => 'required',
'distance' => 'required_if:order_type,delivery',
'address' => 'required_if:order_type,delivery',
'longitude' => 'required_if:order_type,delivery',
'latitude' => 'required_if:order_type,delivery',
]);
if ($validator->fails()) {
return response()->json(['errors' => Helpers::error_processor($validator)], 403);
}
$coupon = null;
$delivery_charge = null;
$schedule_at = $request->schedule_at?\Carbon\Carbon::parse($request->schedule_at):now();
if($request->schedule_at && $schedule_at < now())
{
return response()->json([
'errors' => [
['code' => 'order_time', 'message' => trans('messages.you_can_not_schedule_a_order_in_past')]
]
], 406);
}
$restaurant = Restaurant::with('discount')->whereTime('opening_time','<=',$schedule_at->format('H:i'))->whereTime('closeing_time','>=',$schedule_at->format('H:i'))->where('id', $request->restaurant_id)->first();
if(!$restaurant)
{
return response()->json([
'errors' => [
['code' => 'order_time', 'message' => trans('messages.restaurant_is_closed_at_order_time')]
]
], 406);
}
if($request->schedule_at && !$restaurant->schedule_order)
{
return response()->json([
'errors' => [
['code' => 'schedule_at', 'message' => trans('messages.schedule_order_not_available')]
]
], 406);
}
if ($request['coupon_code']) {
$coupon = Coupon::active()->where(['code' => $request['coupon_code']])->first();
if (isset($coupon)) {
$staus = CouponLogic::is_valide($coupon, $request->user()->id ,$request['restaurant_id']);
if($staus==407)
{
return response()->json([
'errors' => [
['code' => 'coupon', 'message' => trans('messages.coupon_expire')]
]
], 407);
}
else if($staus==406)
{
return response()->json([
'errors' => [
['code' => 'coupon', 'message' => trans('messages.coupon_usage_limit_over')]
]
], 406);
}
else if($staus==404)
{
return response()->json([
'errors' => [
['code' => 'coupon', 'message' => trans('messages.not_found')]
]
], 404);
}
if($coupon->coupon_type == 'free_delivery')
{
$delivery_charge = 0;
$coupon = null;
}
} else {
return response()->json([
'errors' => [
['code' => 'coupon', 'message' => 'not found!']
]
], 401);
}
}
$per_km_shipping_charge = (float)BusinessSetting::where(['key' => 'per_km_shipping_charge'])->first()->value;
$minimum_shipping_charge = (float)BusinessSetting::where(['key' => 'minimum_shipping_charge'])->first()->value;
$original_delivery_charge = ($request->distance * $per_km_shipping_charge > $minimum_shipping_charge) ? $request->distance * $per_km_shipping_charge : $minimum_shipping_charge;
if($request['order_type'] != 'take_away' && !$restaurant->free_delivery && $delivery_charge == null)
{
$delivery_charge = ($request->distance * $per_km_shipping_charge > $minimum_shipping_charge) ? $request->distance * $per_km_shipping_charge : $minimum_shipping_charge;
}
if($request->latitude && $request->longitude)
{
$point = new Point($request->latitude,$request->longitude);
$zone = Zone::where('id', $restaurant->zone_id)->contains('coordinates', $point)->first();
if(!$zone)
{
$errors = [];
array_push($errors, ['code' => 'coordinates', 'message' => trans('messages.out_of_coverage')]);
return response()->json([
'errors' => $errors
], 403);
}
}
$address = [
'contact_person_name' => $request->contact_person_name?$request->contact_person_name:$request->user()->f_name.' '.$request->user()->f_name,
'contact_person_number' => $request->contact_person_number?$request->contact_person_number:$request->user()->phone,
'address_type' => $request->address_type?$request->address_type:'Delivery',
'address' => $request->address,
'longitude' => (string)$request->longitude,
'latitude' => (string)$request->latitude,
];
$total_addon_price = 0;
$product_price = 0;
$restaurant_discount_amount = 0;
$order_details = [];
$order = new Order();
$order->id = 100000 + Order::all()->count() + 1;
$order->user_id = $request->user()->id;
$order->order_amount = $request['order_amount'];
$order->payment_status = 'unpaid';
$order->order_status = $request['payment_method']=='digital_payment'?'failed':'pending';
$order->coupon_code = $request['coupon_code'];
$order->payment_method = $request->payment_method;
$order->transaction_reference = null;
$order->order_note = $request['order_note'];
$order->order_type = $request['order_type'];
$order->restaurant_id = $request['restaurant_id'];
$order->delivery_charge = $delivery_charge??0;
$order->original_delivery_charge = $original_delivery_charge;
$order->delivery_address = json_encode($address);
$order->schedule_at = $schedule_at;
$order->scheduled = $request->schedule_at?1:0;
$order->otp = rand(1000, 9999);
$order->pending = now();
$order->created_at = now();
$order->updated_at = now();
foreach ($request['cart'] as $c) {
/*foreach (json_decode($product['variations'], true) as $var) {
if ($type == $var['type'] && $var['stock'] < $c['quantity']) {
$validator->getMessageBag()->add('stock', 'Stock is insufficient! available stock ' . $var['stock']);
}
}*/
if ($c['item_campaign_id'] != null) {
$product = ItemCampaign::find($c['item_campaign_id']);
if ($product) {
$type = $c['variation'][0]['type'];
foreach (json_decode($product['variations'], true) as $var) {
if ($type == $var['type'] && $var['stock'] < $c['quantity']) {
$validator->getMessageBag()->add('stock', 'Stock is insufficient! available stock ' . $var['stock']);
}
else {
$price = $product['price'];
}
}
/*if (count(json_decode($product['variations'], true)) > 0) {
$price = Helpers::variation_price($product, json_encode($c['variation']));
}*/
$product->tax = $restaurant->tax;
$product = Helpers::product_data_formatting($product);
$addon_data = Helpers::calculate_addon_price(\App\Models\AddOn::whereIn('id',$c['add_on_ids'])->get(), $c['add_on_qtys']);
$or_d = [
'food_id' => null,
'item_campaign_id' => $c['item_campaign_id'],
'food_details' => json_encode($product),
'quantity' => $c['quantity'],
'price' => $price,
'tax_amount' => Helpers::tax_calculate($product, $price),
'discount_on_food' => Helpers::product_discount_calculate($product, $price, $restaurant),
'discount_type' => 'discount_on_product',
'variant' => json_encode($c['variant']),
'is_stock_decreased' => 1,
'variation' => json_encode($c['variation']),
'add_ons' => json_encode($addon_data['addons']),
'total_add_on_price' => $addon_data['total_add_on_price'],
'created_at' => now(),
'updated_at' => now()
];
$order_details[] = $or_d;
$total_addon_price += $or_d['total_add_on_price'];
$product_price += $price*$or_d['quantity'];
$restaurant_discount_amount += $or_d['discount_on_food']*$or_d['quantity'];
} else {
return response()->json([
'errors' => [
['code' => 'campaign', 'message' => 'not found!']
]
], 401);
}
} else {
$product = Food::find($c['food_id']);
if ($product) {
if (count(json_decode($product['variations'], true)) > 0) {
$price = Helpers::variation_price($product, json_encode($c['variation']));
} else {
$price = $product['price'];
}
$product->tax = $restaurant->tax;
$product = Helpers::product_data_formatting($product);
$addon_data = Helpers::calculate_addon_price(\App\Models\AddOn::whereIn('id',$c['add_on_ids'])->get(), $c['add_on_qtys']);
$or_d = [
'food_id' => $c['food_id'],
'item_campaign_id' => null,
'food_details' => json_encode($product),
'quantity' => $c['quantity'],
'price' => $price,
'is_stock_decreased' => 1,
'tax_amount' => Helpers::tax_calculate($product, $price),
'discount_on_food' => Helpers::product_discount_calculate($product, $price, $restaurant),
'discount_type' => 'discount_on_product',
'variant' => json_encode($c['variant']),
'variation' => json_encode($c['variation']),
'add_ons' => json_encode($addon_data['addons']),
'total_add_on_price' => $addon_data['total_add_on_price'],
'created_at' => now(),
'updated_at' => now()
];
//stock update code
$type = $c['variation'][0]['type'];
$var_store = [];
foreach (json_decode($product['variations'], true) as $var) {
if ($type == $var['type']) {
$var['stock'] -= $c['quantity'];
}
array_push($var_store, $var);
}
Product::where(['id' => $product['id']])->update([
'variations' => json_encode($var_store),
'total_stock' => $product['total_stock'] - $c['quantity'],
]);
DB::table('order_details')->insert($or_d);
$total_addon_price += $or_d['total_add_on_price'];
$product_price += $price*$or_d['quantity'];
$restaurant_discount_amount += $or_d['discount_on_food']*$or_d['quantity'];
$order_details[] = $or_d;
} else {
return response()->json([
'errors' => [
['code' => 'food', 'message' => 'not found!']
]
], 401);
}
}
And tried mentioning variable like this 'total_stock' =>$total_stock but still not working
I am creating a website which have two database table of client and freelancer. Now i have to integrate everything, like profile credentials, password, images etc.
initially the application have two different files(in two different folders) that handels. The change in passwords and other profile credentials such as name, username and email of freelancer and client.
So to integrate everything into single file, i am executing all the sql queries of freelancer table in the client one. All the profile credentials get updated successfully, but not the password. I dont understand why?
This is Client/profile.php file
$client = new Client();
$freelancer = new Freelancer();
//Check if Client is logged in
if (!$client->isLoggedIn() && !$freelancer->isLoggedIn()) {
Redirect::to('../index.php');
}
//Get Instructor's Data
$query = DB::getInstance()->get("client", "*", ["clientid" => $client->data()->clientid]);
if ($query->count()) {
foreach ($query->results() as $row) {
$nid = $row->id;
$name = $row->name;
$username = $row->username;
$email = $row->email;
$bgimage = $row->bgimage;
$phone = $row->phone;
}
}
//Edit Profile Data
if (isset($_POST['profile'])) {
if (Input::exists()) {
if (Token::check(Input::get('token'))) {
$errorHandler = new ErrorHandler;
$validator = new Validator($errorHandler);
$validation = $validator->check($_POST, [
'username' => [
'required' => true,
'maxlength' => 20,
'minlength' => 2
],
'name' => [
'required' => true,
'maxlength' => 100,
'minlength' => 2
],
'email' => [
'required' => true,
'maxlength' => 255,
'email' => true,
],
'phone' => [
'required' => false,
'maxlength' => 10,
'minlength' => 10
]
]);
if (!$validation->fails()) {
$client->update([
'name' => Input::get('name'),
'username' => Input::get('username'),
'email' => Input::get('email'),
'phone' => Input::get('phone')
], [
'clientid' => $client->data()->clientid
]);
if (count($client) > 0) {
$noError = true;
}
else {
$hasError = true;
}
$freelancer->update([
'name' => Input::get('name'),
'username' => Input::get('username'),
'email' => Input::get('email'),
'phone' => Input::get('phone')
], [
'freelancerid' => $freelancer->data()->freelancerid
]);
if (count($freelancer) > 0) {
$noError = true;
} else {
$hasError = true;
}
}
else {
$error = '';
foreach ($validation->errors()->all() as $err) {
$str = implode(" ", $err);
$error .= '
<div class="alert alert-danger fade in">
×
<strong>Error!</strong> ' . $str . '
</div>
';
}
}
}
}
}
/*Edit Password Data*/
if (isset($_POST['register'])) {
if (Input::exists()) {
if (Token::check(Input::get('token'))) {
$errorHandler = new ErrorHandler;
$validator = new Validator($errorHandler);
$validation = $validator->check($_POST, [
'password_current' => [
'required' => true,
'maxlength' => 300
],
'password_new' => [
'required' => true,
'minlength' => 6
],
'password_new_again' => [
'required' => true,
'match' => 'password_new'
]
]);
if (!$validation->fails()) { //working fine
if ( (Hash::make(Input::get('password_current'), $client->data()->salt) !== $client->data()->password) && (Hash::make(Input::get('password_current'), $freelancer->data()->salt) !== $freelancer->data()->password) ){
$hasError = true;
}
else {
$salt = Hash::salt(32);
$changed_password = Hash::make(Input::get('password_new'), $salt);
$client->update([
'password' => $changed_password,
'salt' => $salt
], [
'clientid' => $client->data()->clientid
]);
$noError = true;
}
if (!$validation->fails()) { //not working
if (Hash::make(Input::get('password_current'), $freelancer->data()->salt) !== $freelancer->data()->password) {
$hasError = true;
}
else {
$salt = Hash::salt(32);
$freelancer->update([
'password' => Hash::make(Input::get('password_new'), $salt),
'salt' => $salt
],[
'freelancerid' => $freelancer->data()->freelancerid
]);
$noError = true;
}
}
else {
$error = '';
foreach ($validation->errors()->all() as $err) {
$str = implode(" ", $err);
$error .= '
<div class="alert alert-danger fade in">
×
<strong>Error!</strong> ' . $str . '
</div>
';
}
}
}
}
}
This is Freelancer/profile.php file code to change password
if(isset($_POST['register'])){
if (Input::exists()) {
if (Token::check(Input::get('token'))) {
$errorHandler = new ErrorHandler;
$validator = new Validator($errorHandler);
$validation = $validator->check($_POST, [
'password_current' => [
'required' => true,
'maxlength' => 300
],
'password_new' => [
'required' => true,
'minlength' => 6
],
'password_new_again' => [
'required' => true,
'match' => 'password_new'
]
]);
if (!$validation->fails()) {
if (Hash::make(Input::get('password_current'), $freelancer->data()->salt) !== $freelancer->data()->password) {
$hasError = true;
}
else {
$salt = Hash::salt(32);
$freelancer->update([
'password' => Hash::make(Input::get('password_new'), $salt),
'salt' => $salt
],[
'freelancerid' => $freelancer->data()->freelancerid
]);
$noError = true;
}
}
else {
$error = '';
foreach ($validation->errors()->all() as $err) {
$str = implode(" ",$err);
$error .= '
<div class="alert alert-danger fade in">
×
<strong>Error!</strong> '.$str.'
</div>
';
}
}
}
}
}
My question is if the query to change username, email and phone number is working fine, why the password change for freelancer is not working?
The hash function algorithm can give two encrypted strings for a same inputed string so when i am calling the function two times for the client and the freelancer, two different strings and getting stored in the data base.
i am having 3-4 for each in my code which all use Eloquent and in all of them i get the same error
Trying to get property of non-object
when i dd the first argument of foreach which is an eloquent it returns an array of json with all the data in database of that table so its not returning null though i know it may break or bring null while in a foreach loop but i dont know where place one of them with model and controller here so here is the loop it self
<?php foreach(\App\Menu::all()->where('slug','main')->first()->items as $top_menu): ?>
<li class="dropdown">
<a href="<?php echo e(URL($top_menu->link)); ?>" <?php if($top_menu->link_blank): ?> target="_blank" <?php endif; ?>>
<?php echo e($top_menu->title); ?>
</a>
</li>
<?php endforeach; ?>
and here is my controller
class MenuItemsController extends AdminController
{
var $object = 'menu_items';
var $route_name = 'menu_items';
var $object_title = 'item';
var $object_titles = 'items';
var $attachments_config = [
'main_image' => [],
'default_thumb_sizes' => [],
'require' => ['main_image']
];
var $dt_fields_db = [];
var $dt_fields_heading = ['شناسه','منو','عنوان','موقعیت','نمایش','ثبت','عملیات'];
var $dt_fields_full = [
'id' => ['menu_items.id'],
'menu_title' => ['menus.title'],
'title' => ['menu_items.title'],
'position' => ['menu_items.position'],
'display' => ['menu_items.display'],
'created_at' => ['menu_items.created_at'],
'actions' => ['actions']
];
var $messages = array();
public function __construct() {
parent::__construct();
view()->share(['attachments_config' => $this->attachments_config]);
}
function index() {
$data['extra_assets'] = array(
array('type' => 'css','path' => 'datatables/datatables.bootstrap.css'),
array('type' => 'js','path' => 'datatables/jquery.dataTables.min.js'),
array('type' => 'js','path' => 'datatables/datatables.bootstrap.js'),
array('type' => 'script','path' => 'pagescripts/shared/datatables_script.php'),
);
$data['dt_fields_heading'] = $this->dt_fields_heading;
$data['dt_fields'] = $this->dt_fields_full;
$data['heading'] = $this->object_titles;
return view('admin.shared.datatable',$data);
}
function datatable() {
$this->dt_filtered_actions = dt_actions_filter($this->route_name,['edit','delete']);
$objects = DB::table('menu_items')
->join('menus', 'menu_items.menu_id','=', 'menus.id')
->select([
'menu_items.id',
'menus.title as menu_title',
'menu_items.title',
'menu_items.display',
'menu_items.position',
'menu_items.created_at'
]);
return Datatables::of($objects)
->editColumn('display', function($model) {return label_status($model->display);})
->editColumn('created_at', function($model) {return ($date = jDate::forge($model->created_at)->format('%H:%M:%S - %y/%m/%d'))?$date:"";})
->addColumn('actions', function($model) {
return dt_actions($this->route,$model->id,$this->dt_filtered_actions);
})
->make(true);
}
function add() {
$data['extra_assets'] = array(
array('type' => 'js','path' => 'select2/select2.full.min.js'),
array('type' => 'css','path' => 'select2/select2.min.css'),
array('type' => 'css','path' => 'select2/select2-bootstrap.css'),
array('type' => 'helper','name' => 'select2'),
);
$data['menus'] = Menu::all()->lists('title','id');
$data['heading'] = 'add'.$this->object_title;
return view('admin.'.$this->route_name.'.add',$data);
}
function create(\Illuminate\Http\Request $request) {
$validator = Validator::make($request->all(), [
'menu_id' => 'required',
]);
if ($validator->fails()) {
return back()->withErrors($validator)->withInput();
}
$input = $request->all();
$input['display'] = (isset($input['display']))?$input['display']:0;
$menu = Menu::find($input['menu_id']);
if($menu->items->count() == $menu->capacity) {
$this->messages[] = array('type' => 'danger', 'text' => 'menu is full');
Session::flash('messages', $this->messages);
return back();
}
MenuItem::create($input);
$this->messages[] = array('type' => 'success', 'text' => 'success.');
Session::flash('messages', $this->messages);
return redirect()->route('admin.'.$this->route_name.'.index');
}
function edit(MenuItem $MenuItem) {
$data['object'] = $MenuItem;
$data['extra_assets'] = array(
array('type' => 'script','path' => 'pagescripts/shared/image_preview_script.php'),
array('type' => 'js','path' => 'select2/select2.full.min.js'),
array('type' => 'css','path' => 'select2/select2.min.css'),
array('type' => 'css','path' => 'select2/select2-bootstrap.css'),
array('type' => 'helper','name' => 'select2'),
array('type' => 'js','path' => 'ckeditor/ckeditor.js'),
array('type' => 'js','path' => 'ckeditor/config.js'),
array('type' => 'js','path' => 'ckfinder/ckfinder.js'),
array('type' => 'js','path' => 'ckfinder/config.js'),
array('type' => 'script','path' => 'pagescripts/shared/ckeditor_script.php'),
);
$data['menus'] = Menu::all()->lists('title','id');
$data['heading'] = 'edit'.$this->object_title;
return view('admin.'.$this->route_name.'.edit',$data);
}
function update(MenuItem $MenuItem,\Illuminate\Http\Request $request) {
$validator = Validator::make($request->all(), [
'menu_id' => 'required',
]);
if ($validator->fails()) {
return redirect()->back()
->withErrors($validator)
->withInput();
}
$input = $request->all();
$input['display'] = (isset($input['display']))?$input['display']:0;
$MenuItem->update($input);
$this->messages[] = array('type' => 'success', 'text' => 'success.');
Session::flash('messages', $this->messages);
return redirect()->back();
}
function delete(\Illuminate\Http\Request $requests,MenuItem $MenuItem) {
if($requests->ajax() && $MenuItem->delete()) {
return "OK";
} else {
return "ERROR";
}
}
function deleteall(\Illuminate\Http\Request $requests) {
$ids = $requests->get('ids');
if($requests->ajax()) {
foreach (explode(',',$ids) as $id) {
if(intval($id)) MenuItem::find($id)->delete();
}
return "OK";
} else {
return "ERROR";
}
}
}
the problem was because my database table didn't got any row by the slug of menu and the query returned null and that error happens that error generally happens when your query returns null thanks all for help
i have a mistake uploading some images on "multiple upload". If i try to upload the galeries without these images the widget works correctly.
The Image: http://s27.postimg.org/a6qosyctv/Esta_Imagen_Tira_Error.jpg
My form:
$form = ActiveForm::begin([
'id' => 'Item',
'layout' => 'horizontal',
'enableClientValidation' => false,
'errorSummaryCssClass' => 'error-summary alert alert-error',
'options' => ['enctype'=>'multipart/form-data']
]);
$form->field($gallery, 'images[]')->widget(\kartik\file\FileInput::classname(), [
'options' => [
'multiple' => true,
],
'pluginOptions' => [
'uploadUrl' => 'javascript:;',
'showCaption' => false,
'showUpload' => false,
'overwriteInitial' => false,
'allowedFileExtensions' => ['jpg', 'jpeg', 'png'],
'layoutTemplates' => [
'actionUpload' => '',
],
'browseIcon' => '',
'browseLabel' => Yii::t('app', 'Select Files'),
'browseClass' => 'btn btn-block',
'removeLabel' => Yii::t('app', 'Remove All File'),
'removeClass' => 'btn btn-block',
],
]);
My controller:
public function actionCreate()
{
$model = new Hotel();
$model->setCurrentLanguage();
$model->itemType = IElement::ITEM_TYPE_HOTEL;
if ($model->load($_POST)) {
$model->coverPhoto = UploadedFile::getInstance($model, 'coverPhoto');
if ($model->save()) {
if (isset($_POST['Gallery'])) {
$gallery = new Gallery();
$gallery->setAttributes($_POST['Gallery']);
$gallery->idElement = $model->idItem;
$gallery->itemType = IElement::ITEM_TYPE_HOTEL;
$gallery->images = UploadedFile::getInstances($gallery, 'images');
$gallery->save();
}
return $this->redirect(['index']);
}
}
return $this->render('create', [
'model' => $model,
'gallery' => new Gallery(),
]);
}
Gallery Model:
public $images = [];
public function rules()
{
return array_merge(parent::rules(), [
[['images', 'removedImages'], 'safe']
]);
}
public function save($runValidation = true, $attributeNames = null)
{
$transaction = $this->getDb()->beginTransaction();
if(parent::save($runValidation, $attributeNames)){
foreach($this->images as $image){
/* #var UploadedFile $image */
if(!GalleryItem::generateFromImage($image, $this)){
$transaction->rollBack();
return false;
}
}
if(strlen($this->removedImages) > 0){
foreach(explode(',', $this->removedImages) as $itemId){
$albumItem = GalleryItem::findOne($itemId);
if($albumItem instanceof GalleryItem && !$albumItem->delete()){
$transaction->rollBack();
return false;
}
}
}
$transaction->commit();
return true;
}
$transaction->rollBack();
return false;
}
Gallery Item Model:
public static function generateFromImage($imageFile, $gallery)
{
$image = new self;
$image->idGallery = $gallery->primaryKey;
$image->galleryItemOrder = time();
$path = $image->getBasePath();
if(!file_exists($path)) {
mkdir($path, 0777, true);
}
$name = uniqid().'_'.strtr($imageFile->name, [' '=>'_']);
$imageFile->saveAs($path.DIRECTORY_SEPARATOR.$name);
$image->picture = $name;
// var_dump($image->attributes);die();
if(!$image->save()){
#unlink($path.DIRECTORY_SEPARATOR.$name);
return false;
}
return true;
}
I got trouble inputing the radio button value to database, when i choose "submit" it won't add into database. This is the form view:
<?php
$form = array(
'no pengujian' => array(
'name' => 'NO_PENGUJIAN',
'size' => '30',
'class' => 'form_field',
'value' => set_value('NO_PENGUJIAN', isset($form_value['NO_PENGUJIAN']))),
'id kendaraan' => array(
'name' => 'ID_KENDARAAN',
'size' => '30',
'class' => 'form_field',
'value' => set_value('ID_KENDARAAN', isset($form_value['ID_KENDARAAN']))),
'no kendaraan' => array(
'name' => 'NO_KENDARAAN',
'size' => '30',
'class' => 'form_field',
'value' => set_value('NO_KENDARAAN', isset($form_value['NO_KENDARAAN']))),
'lampu' => array(
'name' => 'LAMPU',
'size' => '30',
'class' => 'radio',
'value' => set_value('LAMPU', isset($_POST['LAMPU']))),
'submit' => array(
'name' => 'submit',
'id' => 'submit',
'value' => 'Simpan'
)
);
?>
<h2><?php echo $breadcrumb ?></h2>
<!-- pesan start -->
<?php if (! empty($pesan)) : ?>
<div class="pesan">
<?php echo $pesan; ?>
</div>
<?php endif ?>
<!-- pesan end -->
<!-- form start -->
<?php echo form_open($form_action); ?>
<p>
<?php echo form_label('No Pengujian', 'NO_PENGUJIAN'); ?>
<?php echo form_input($form['no pengujian']); ?>
</p>
<?php echo form_error('NO_PENGUJIAN', '<p class = "field_error">', '</p>');?>
<p>
<?php echo form_label('Id Kendaraan', 'ID_KENDARAAN'); ?>
<?php echo form_input($form['id kendaraan']); ?>
</p>
<?php echo form_error('ID_KENDARAAN', '<p class="field_error">', '</p>'); ?>
<p>
<?php echo form_label('No Kendaraan', 'NO_KENDARAAN'); ?>
<?php echo form_input($form['no kendaraan']); ?>
</p>
<?php echo form_error('NO_KENDARAAN', '<p class="field_error">', '</p>'); ?>
<p>
<?php echo form_label('Lampu', 'LAMPU'); ?>
<input type ="radio" name = "lulus" value="Lulus"/> Lulus
<input type ="radio" name = "lulus" value= "Gagal"/> Gagal
</p>
<p>
<?php echo form_submit($form['submit']); ?>
<?php echo anchor('pengujian', 'Batal', array('class' => 'cancel')) ?>
</p>
<?php echo form_close(); ?>
This is the controller (tambah is "insert" function to database)
<?php if (!defined('BASEPATH')) exit ('No direct script access allowed');
class Pengujian extends MY_Controller
{
public $data = array(
'modul' => 'pengujian',
'breadcrumb' => 'Pengujian',
'pesan' => '',
'pagination' => '',
'tabel_data' => '',
'main_view' => 'view_pengujian/pengujian_view',
'form_action' => '',
'form_value' => '',
'option_uji' => '',
);
public function __construct()
{
parent::__construct();
$this->load->model('Pengujian_model', 'pengujian', TRUE);
$this->load->helper('form');
//$this->load->model('Penguji_model', 'penguji', TRUE);
}
public function index($offset = 0)
{
$this->session->unset_userdata('no_pengujian_sekarang', '');
$pengujian = $this->pengujian->cari_semua($offset);
if ($pengujian)
{
$tabel = $this->pengujian->buat_tabel($pengujian);
$this->data['tabel_data'] = $tabel;
$this->data['pagination'] = $this->pengujian->paging(site_url('pengujian/halaman'));
}
else
{
$this->data['pesan'] = 'Tidak ada data pengujian';
}
$this->load->view('template', $this->data);
}
public function tambah()
{
$this->data['breadcrumb'] = 'Pengujian > Tambah';
$this->data['main_view'] = 'view_pengujian/pengujian_form';
$this->data['form_action'] = 'pengujian/tambah';
//$penguji = $this->penguji->cari_semua();
//if($penguji)
//{
// foreach($penguji as $row)
// {
// $this->data['option_pengujian'][$row->id_penguji] = $row->penguji;
//}
//}
//else
//{
$this->data['option_pengujian']['00'] = '-';
// $this->data['pesan'] = 'Data penguji tidak tersedia. Silahkan isi dahulu data penguji.';
// if submit
if($this->input->post('submit'))
{
if($this->pengujian->validasi_tambah())
{
if($this->pengujian->tambah())
{
$this->session->set_flashdata('pesan', ' Proses tambah data berhasil');
redirect('pengujian');
}
else
{
$this->data['pesan'] = 'Proses tambah data gagal';
$this->load->view('template', $this->data);
}
}
else
{
$this->load->view('template', $this->data);
}
}
else
{
$this->load->view('template', $this->data);
}
}
This is the model:
<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
class Pengujian_model extends CI_Model
{
public $db_tabel ='pengujian';
public $per_halaman = 100;
public $offset = 0;
public function cari_semua($offset = 0)
{
if (is_null($offset) || empty($offset))
{
$this->offset = 0;
}
else
{
$this->offset = ($offset * $this->per_halaman) - $this->per_halaman;
}
return $this->db->select('NO_PENGUJIAN, ID_KENDARAAN, NO_KENDARAAN, LAMPU, EMISI, REM, WAKTU_UJI')
->from($this->db_tabel)
->limit($this->per_halaman, $this->offset)
->order_by('NO_PENGUJIAN', 'ASC')
->get()
->result();
}
public function buat_tabel($data)
{
$this->load->library('table');
$tmpl = array('row_alt_start' => '<tr class="zebra">');
$this->table->set_template($tmpl);
$this->table->set_heading('No', 'No Pengujian', 'Id Kendaraan', 'No Kendaraan', 'Lampu','Emisi','Rem', 'Waktu Uji', 'Aksi');
$no = 0 + $this->offset;
foreach ($data as $row)
{
$this->table->add_row(
++$no,
$row->NO_PENGUJIAN,
$row->ID_KENDARAAN,
$row->NO_KENDARAAN,
$row->LAMPU,
$row->EMISI,
$row->REM,
$row->WAKTU_UJI,
anchor('pengujian/edit/'.$row->NO_PENGUJIAN,'Edit',array('class' => 'edit')).' '.
anchor('pengujian/hapus/'.$row->NO_PENGUJIAN,'Hapus',array('class' => 'delete','onclick'=>"return confirm('Anda yakin menghapus data ini?')")));
}
$tabel = $this->table->generate();
return $tabel;
}
public function paging($base_url)
{
$this->load->library('pagination');
$config = array(
'base_url' => $base_url,
'total_rows' => $this->hitung_semua(),
'per_page' => $this->per_halaman,
'num_links' => 4,
'use_page_number' => TRUE,
'first link' => '|< First',
'last link' => 'Last >|',
'next link' => 'Next >',
'prev_link' => '< Prev',
);
$this->pagination->initialize($config);
return $this->pagination->create_links();
}
public function hitung_semua()
{
return $this->db->count_all($this->db_tabel);
}
private function load_form_rules_tambah()
{
$form = array(
array(
'field' => 'NO_PENGUJIAN',
'label' => 'no pengujian',
'rules' => 'required'
),
array(
'field' => 'ID_KENDARAAN',
'label' => 'id kendaraan',
'rules' => 'required'
),
array(
'field' => 'NO_KENDARAAN',
'label' => 'no kendaraan',
'rules' => 'required'
),
array(
'field' => 'LAMPU',
'label' => 'lampu',
'rules' => 'required'
),
);
return $form;
}
public function validasi_tambah()
{
$form = $this->load_form_rules_tambah();
$this->form_validation->set_rules($form);
if($this->form_validation->run())
{
return TRUE;
}
else
{
return FALSE;
}
}
public function tambah()
{
$pengujian = array(
'NO_PENGUJIAN' => $this->input->post('NO_PENGUJIAN'),
'ID_KENDARAAN' => $this->input->post('ID_KENDARAAN'),
'NO_KENDARAAN' => $this->input->post('NO_KENDARAAN'),
'LAMPU' => $this->input->post('lampu[]'),
//'EMISI' => $this->input->post('EMISI'),
//'REM' => $this->input->post('REM')
);
$lulus = $_POST["lulus"];
//$statement = "INSERT INTO pengujian VALUES($lulus)"
$this->db->insert($this->db_tabel, $pengujian);
if($this->db->affected_rows() > 0)
{
return TRUE;
}
else
{
return FALSE;
}
}
I got no trouble in the formfield. The trouble is the radio button "lampu"
The best thing to do, I think, is to check where it's going wrong. I usually do this, in this case, by checking if the value is being passed back to the controller and model. This way you understand better what's going on inside your code. Do something like this:
In the model:
public function tambah()
{
// Check to see if we get a value. If not, do the same in the controller
var_dump($this->input->post('lampu'));
exit;
$pengujian = array(
'NO_PENGUJIAN' => $this->input->post('NO_PENGUJIAN'),
'ID_KENDARAAN' => $this->input->post('ID_KENDARAAN'),
'NO_KENDARAAN' => $this->input->post('NO_KENDARAAN'),
'LAMPU' => $this->input->post('lampu[]'),
//'EMISI' => $this->input->post('EMISI'),
//'REM' => $this->input->post('REM')
);
$lulus = $_POST["lulus"];
//$statement = "INSERT INTO pengujian VALUES($lulus)"
$this->db->insert($this->db_tabel, $pengujian);
if($this->db->affected_rows() > 0)
{
return TRUE;
}
else
{
return FALSE;
}
}
I hope this helps a bit....