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
Related
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.
I have migrated my Stripe checkout from legacy version to the new one. The payment does work, but the success redirect URL as well as the DB update does not work.
When I send the request I get redirected to my main page instead of the user subscription page.
Also I do get the error:
Could not determine the URL to request: StripeCustomer instance has invalid ID: (no ID)
I already did some research and also visited the migration documentation from Stripe:
https://stripe.com/docs/payments/checkout/migration
But I do not get the error.
My guess is it is between the lines:
//$payer_id = $customer->id;
$payer_email = $customer->email;
$updateTrx = $trx->update([
'total_price' => $total,
'payment_gateway_id' => $payment_gateway_id,
'payment_id' => $payment_id,
//'payer_id' => $payer_id,
'payer_email' => $payer_email,
'status' => 2,
]);
if ($updateTrx) {
CheckoutController::updateSubscription($trx);
toastr()->success(lang('Payment made successfully', 'checkout'));
return redirect()->route('user.subscription');
}
from:
<?php
namespace App\Http\Controllers\Frontend\Gateways;
use App\Http\Controllers\Controller;
use App\Http\Controllers\Frontend\User\CheckoutController;
use Exception;
use Illuminate\Http\Request;
use Stripe\Checkout\Session;
use Stripe\Customer;
use Stripe\Stripe;
class StripeCheckoutController extends Controller
{
public static function process($trx)
{
if ($trx->status != 0) {
$data['error'] = true;
$data['msg'] = lang('Invalid or expired transaction', 'checkout');
return json_encode($data);
}
if ($trx->plan->interval == 0) {
$planInterval = '(Monthly)';
} elseif ($trx->plan->interval == 1) {
$planInterval = '(Yearly)';
} elseif ($trx->plan->interval == 2) {
$planInterval = '(Lifetime)';
}
$paymentName = "Payment for subscription " . $trx->plan->name . " Plan " . $planInterval;
$gatewayFees = ($trx->total_price * paymentGateway('stripe_checkout')->fees) / 100;
$totalPrice = round(($trx->total_price + $gatewayFees), 2);
$priceIncludeFees = str_replace('.', '', ($totalPrice * 100));
$paymentDeatails = [
'customer_email' => $trx->user->email,
'payment_method_types' => [
'card',
],
'line_items' => [[
'price_data' => [
'currency' => currencyCode(),
'unit_amount' => $priceIncludeFees,
'product_data' => [
'name' => settings('website_name'),
'description' => $paymentName,
],
],
'quantity' => 1,
]],
'mode' => 'payment',
'cancel_url' => route('user.subscription'),
'success_url' => route('ipn.stripe_checkout') . '?session_id={CHECKOUT_SESSION_ID}',
];
try {
Stripe::setApiKey(paymentGateway('stripe_checkout')->credentials->secret_key);
$session = Session::create($paymentDeatails);
if ($session) {
$trx->update(['fees_price' => $gatewayFees, 'payment_id' => $session->id]);
$data['error'] = false;
$data['redirectUrl'] = $session->url;
return json_encode($data);
}
} catch (\Exception $e) {
$data['error'] = true;
$data['msg'] = $e->getMessage();
return json_encode($data);
}
}
public function ipn(Request $request)
{
$session_id = $request->session_id;
try {
Stripe::setApiKey(paymentGateway('stripe_checkout')->credentials->secret_key);
$trx = \App\Models\Transaction::where([['user_id', userAuthInfo()->id], ['payment_id', $session_id], ['status', 1]])->first();
if (is_null($trx)) {
throw new Exception(lang('Invalid or expired transaction', 'checkout'));
}
$session = Session::retrieve($session_id);
//if ($session->payment_status == "paid") {
if ($session->payment_status == "paid") {
$customer = Customer::retrieve($session->customer);
$total = ($trx->total_price + $trx->fees_price);
$payment_gateway_id = paymentGateway('stripe_checkout')->id;
$payment_id = $session->id;
//$payer_id = $customer->id;
$payer_email = $customer->email;
$updateTrx = $trx->update([
'total_price' => $total,
'payment_gateway_id' => $payment_gateway_id,
'payment_id' => $payment_id,
//'payer_id' => $payer_id,
'payer_email' => $payer_email,
'status' => 2,
]);
if ($updateTrx) {
CheckoutController::updateSubscription($trx);
toastr()->success(lang('Payment made successfully', 'checkout'));
return redirect()->route('user.subscription');
}
} else {
throw new Exception(lang('Payment failed', 'checkout'));
}
} catch (\Exception $e) {
toastr()->error($e->getMessage());
return redirect()->route('home');
}
}
}
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'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());
}
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