Laravel 4.2 Trying to authorize User using post method - php

i am trying to make a post request to authorize user.
This is my route.php
Route::post('/user/login', 'OwnerController#login');
Here my login method:
$login_by = Input::get('login_by');
$device_token = Input::get('device_token');
$device_type = Input::get('device_type');
if (Input::has('email') && Input::has('password')) {
$email = Input::get('email');
$password = Input::get('password');
$validator = Validator::make(
array(
'password' => $password,
'email' => $email,
'device_token' => $device_token,
'device_type' => $device_type,
'login_by' => $login_by
), array(
'password' => 'required',
'email' => 'required|email',
'device_token' => 'required',
'device_type' => 'required|in:android,ios',
'login_by' => 'required|in:manual,facebook,google'
)
);
if ($validator->fails()) {
$error_messages = $validator->messages()->all();
$response_array = array('success' => false, 'error' => 'Invalid Input', 'error_code' => 401, 'error_messages' => $error_messages);
$response_code = 200;
Log::error('Validation error during manual login for owner = ' . print_r($error_messages, true));
} else {
if ($owner = Owner::where('email', '=', $email)->first()) {
if (Hash::check($password, $owner->password)) {
if ($login_by !== "manual") {
$response_array = array('success' => false, 'error' => 'Login by mismatch', 'error_code' => 417);
$response_code = 200;
} else {
if ($owner->device_type != $device_type) {
$owner->device_type = $device_type;
}
if ($owner->device_token != $device_token) {
$owner->device_token = $device_token;
}
$owner->token = generate_token();
$owner->token_expiry = generate_expiry();
$owner->save();
/* SEND REFERRAL & PROMO INFO */
$settings = Settings::where('key', 'referral_code_activation')->first();
$referral_code_activation = $settings->value;
if ($referral_code_activation) {
$referral_code_activation_txt = "referral on";
} else {
$referral_code_activation_txt = "referral off";
}
$settings = Settings::where('key', 'promotional_code_activation')->first();
$promotional_code_activation = $settings->value;
if ($promotional_code_activation) {
$promotional_code_activation_txt = "promo on";
} else {
$promotional_code_activation_txt = "promo off";
}
/* SEND REFERRAL & PROMO INFO */
$code_data = Ledger::where('owner_id', '=', $owner->id)->first();
$response_array = array(
'success' => true,
'id' => $owner->id,
'first_name' => $owner->first_name,
'last_name' => $owner->last_name,
'phone' => $owner->phone,
'email' => $owner->email,
'picture' => $owner->picture,
'bio' => $owner->bio,
'address' => $owner->address,
'state' => $owner->state,
'country' => $owner->country,
'zipcode' => $owner->zipcode,
'login_by' => $owner->login_by,
'social_unique_id' => $owner->social_unique_id,
'device_token' => $owner->device_token,
'device_type' => $owner->device_type,
'timezone' => $owner->timezone,
'token' => $owner->token,
'referral_code' => $code_data->referral_code,
'is_referee' => $owner->is_referee,
'promo_count' => $owner->promo_count,
'is_referral_active' => $referral_code_activation,
'is_referral_active_txt' => $referral_code_activation_txt,
'is_promo_active' => $promotional_code_activation,
'is_promo_active_txt' => $promotional_code_activation_txt,
);
$dog = Dog::find($owner->dog_id);
if ($dog !== NULL) {
$response_array = array_merge($response_array, array(
'dog_id' => $dog->id,
'age' => $dog->age,
'name' => $dog->name,
'breed' => $dog->breed,
'likes' => $dog->likes,
'image_url' => $dog->image_url,
));
}
$response_code = 200;
}
} else {
$response_array = array('success' => false, 'error' => 'Invalid Username and Password', 'error_code' => 403);
$response_code = 200;
}
} else {
$response_array = array('success' => false, 'error' => 'Not a Registered User', 'error_code' => 404);
$response_code = 200;
}
}
return Response::make(json_encode($response_array,JSON_PRETTY_PRINT))->header('Content-Type', "application/json");
but when i tried to access this url from my ios project using AFNETWORKING: Login Link Localhost
I got this error:
URL: http://192.168.1.26/uberx/public/user/login } { status code:
500, headers {
"Cache-Control" = "no-cache";
Connection = close;
"Content-Length" = 4390;
"Content-Type" = "text/html; charset=UTF-8";
Date = "Mon, 08 Feb 2016 09:04:56 GMT";
Server = "Apache/2.4.17 (Win32) OpenSSL/1.0.2d PHP/5.6.14";
"Set-Cookie" = "laravel_session=eyJpdiI6Iis2VnVUN2JWQW9uMEFkcTBkUkJtNWc9PSIsInZhbHVlIjoiVVpMeW1KbkRMblA2K1hSNGpBSHpHaHNhNGt2a3hab1BaNmdPVVQ3NDVlaFBOZnFUM3QrdjR3dWlQUFwvTFZIa3VkT0ZUcldiYUxqNmE1QXNlT3hjRjB3PT0iLCJtYWMiOiIwOTJjZjlkMWVlZjg5NzQ3ZmY3MDA1YjBlYjdhN2U4MmE3M2I5YzUwMDU0Y2E4ZmFlMTkyNzVkZWI2ZDI0MTBmIn0%3D;
expires=Mon, 08-Feb-2016 11:04:57 GMT; Max-Age=7200; path=/;
httponly";
"X-Powered-By" = "PHP/5.6.14"; } }, NSLocalizedDescription=Request failed: unacceptable content-type: text/html}}} 2016-02-08
14:34:43.948 Upper[23084:6636866] Login Response ---> (null)
Is there any specific way to make a webservice like method and print json ? Is there a problem in IOS call or in Web output?
Thanks

Related

How to fix time out issue in FCM?

I'm working on a laravel apis which is consumed by a mobile application. The issue is i am using this library ( https://github.com/kreait/firebase-php ) to send FCM to device Ids. I have 10k device ids in my db. Issue is the code is implemented badly and it gets timedout after 1 minute. I need advice what is the best way to overcome this issue?
I have written this code:
// General Notification
$deviceTokens = PushDevices::all()->pluck( 'device_id' )->toArray();
if ( $request->hasFile( 'file' ) || $request->file ) {
try {
$request->validate( [
'image' => 'image|mimes:jpeg,jpg|max:2048|size:400'
] );
$originName = $request->file( 'file' )->getClientOriginalName();
$fileName = pathinfo( $originName, PATHINFO_FILENAME );
$extension = $request->file( 'file' )->getClientOriginalExtension();
$fileNames = time() . '.' . $extension;
$request->file( 'file' )->move( public_path( 'storage/notification' ), $fileNames );
$notiData = [
'title' => $request->title,
'body' => $request->body,
'imageurl' => $fileNames
];
// Create a copy in database for notifications.
NotificationTable::create( $notiData );
// Initiate token with https
$notification = [
'title' => $validation->safe()->only( 'title' )['title'],
'body' => $validation->safe()->only( 'body' )['body'],
'image' => 'https://example.com/storage/notification/' . $fileNames
];
$data = [
'first_key' => 'First Value',
'second_key' => 'Second Value',
];
$response[] = '';
foreach ( $deviceTokens as $object ) {
// $message = CloudMessage::new()->withTarget('token', $object)->withNotification($notification);
$message = CloudMessage::fromArray( [
'token' => $object,
'notification' => $notification
] );
try {
$sendReport = $this->messaging->send( $message );
$response[] = $sendReport;
} catch ( \Throwable $e ) {
$response[] = $e;
}
}
return response()->json( [ 'status' => true, 'response', $response ], Response::HTTP_ACCEPTED );
} catch ( \Throwable $th ) {
return response()->json( [
'status' => false,
'message' => $th->getMessage()
], 500 );
}}
$batchSize = 1000;
$deviceGroups = array_chunk($deviceTokens, $batchSize);
$notification = ['title' => $validation->safe()->only( 'title' )['title'], 'body' => $validation->safe()->only( 'body' )['body'],];
NotificationTable::create( $notification );
$data = ['first_key' => 'First Value', 'second_key' => 'Second Value',];
$response = array();
foreach ( $deviceTokens as $object ) {
$message = CloudMessage::new()->withTarget( 'token', $object )->withNotification( $notification )->withData( $data );
try {
$sendReport = $this->messaging->send( $message );
$response[] = $sendReport;
} catch ( MessagingException|FirebaseException $e ) {
$response[] = $e;
}
}
return response()->json( [ 'status' => true, 'response', $response ], Response::HTTP_ACCEPTED );
I want to send messages to all 10k devices but am unable to understand how to do it.

Rows not found, Codeiginiter Show Index

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

update stock after order placed in laravel php

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

Why the sql query to update password in not running in a php script of a webpage?

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.

Object of class Illuminate\Validation\Rules\Unique could not be converted to int

I'm trying to use ignore method in laravel to apply validation on updating profile I have use ignore() for this but looks like I have gone somewhere wrong and ended up with this error can you help me out to find this here is my code. Thanks for your insights :)
User Controller
public function editProfile(Request $request) {
$userId=$request->userId;
$phoneNumber=$request->phoneNumber;
if(!$request){
$this->setMeta("422", "Nothing is there for update");
return response()->json($this->setResponse());
}
$validator =Validator::make($request->all(), [
'phoneNumber' => [
'max:10',
Rule::unique('users')->ignore($userId,'userId'),
],
]);
if ($validator->fails()) {
//$response['meta'] = array('code' => "422", 'message' => "Error, please try again");
$errors = $validator->errors();
if ($errors->first('phoneNumber')) {
$message = $errors->first('phoneNumber');
}
$this->setMeta("403", $message);
return response()->json($this->setResponse());
}
$homeTown = $request->homeTown;
$heightInCm=0;
/*$homeTownId= City::where('cityName', $homeTown)->first()->cityId;*/
if($request->userHeight) {
$userHeight=$request->userHeight;
$heightSplit = explode("'", $userHeight, 2);
$feet = $heightSplit[0];
$inches = $heightSplit[1];
$inch=($feet *12)+$inches;
$heightInCm=$inch*2.54;
}
$verticalInCm=0;
/*$homeTownId= City::where('cityName', $homeTown)->first()->cityId;*/
if($request->userVertical) {
$userVertical=$request->userVertical;
$verticalSplit = explode("'", $userVertical, 2);
$feet = $verticalSplit[0];
$inches = $verticalSplit[1];
$inch = ($feet *12)+$inches;
$verticalInCm = $inch*2.54;
}
$data= array(
'profilePic' => $request->profilePic,
'nickName' => $request->nickName,
'phoneNumber' => $request->phoneNumber,
'userHeight' => $heightInCm,
'userWeight' => $request->userWeight,
'userVertical' => $verticalInCm,
'userSchool' => $request->userSchool,
'homeTown' => $homeTown,
'cityId' => $request->cityId,
);
User::where('userId',$request->userId)->update($data);
}
Check if you specifying the correct key for the unique check. Your code says userId is the primary key to compare the given id with, is this correct? If the key is 'id' by default then you can ignore the parameter.
Rule::unique('users')->ignore($$request->userId),
'phoneNumber' => 'max:10|unique:users,id,'.$request->userId,
well after the hell of time spent I finally got the answer.
public function editProfile(Request $request) {
$userId=$request->userid;
$phoneNumber=$request->phoneNumber;
if(!$request){
$this->setMeta("422", "Nothing is there for update");
return response()->json($this->setResponse());
}
$validator = Validator::make(
array(
'phoneNumber' => $phoneNumber,
),
array(
'phoneNumber' =>'size:10', Rule::unique('users')->ignore($request->userId, 'userId'),
)
);
if ($validator->fails()) {
//$response['meta'] = array('code' => "422", 'message' => "Error, please try again");
$errors = $validator->errors();
if ($errors->first('phoneNumber')) {
$message = $errors->first('phoneNumber');
}
$this->setMeta("403", $message);
return response()->json($this->setResponse());
}
$homeTown = $request->homeTown;
$heightInCm=0;
/*$homeTownId= City::where('cityName', $homeTown)->first()->cityId;*/
if($request->userHeight) {
$userHeight=$request->userHeight;
$heightSplit = explode("'", $userHeight, 2);
$feet = $heightSplit[0];
$inches = $heightSplit[1];
$inch=($feet *12)+$inches;
$heightInCm=$inch*2.54;
}
$verticalInCm=0;
/*$homeTownId= City::where('cityName', $homeTown)->first()->cityId;*/
if($request->userVertical) {
$userVertical=$request->userVertical;
$verticalSplit = explode("'", $userVertical, 2);
$feet = $verticalSplit[0];
$inches = $verticalSplit[1];
$inch = ($feet *12)+$inches;
$verticalInCm = $inch*2.54;
}
$data= array(
'profilePic' => $request->profilePic,
'nickName' => $request->nickName,
'phoneNumber' => $request->phoneNumber,
'userHeight' => $heightInCm,
'userWeight' => $request->userWeight,
'userVertical' => $verticalInCm,
'userSchool' => $request->userSchool,
'homeTown' => $homeTown,
'cityId' => $request->cityId,
);
User::where('userId',$request->userId)->update($data);
$this->setMeta("200", "Profile Changes have been successfully saved");
$this->setData("userDetails", $data);
return response()->json($this->setResponse());
}

Categories