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.
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 have a problem, every time I enter or refresh a page it inserts a new record
Controller:
public function cobrar(Request $request,$id){
$data = [
'category_name' => 'datatable',
'page_name' => 'custom',
'has_scrollspy' => 0,
'scrollspy_offset' => '',
];
$cliente = \App\Models\Eventos::first();
$cobros = \App\Models\Cobros::where('turno_id', $request->id)->first();
$evento = \App\Models\Eventos::where('id' , $id)->with('servicio')->first();
$servicio = \App\Models\Servicios::where('id', $evento->servicio_id)->first();
$event = \App\Models\Eventos::find($id);
Cobros::insert([
'turno_id' => $request->input("turno_id"),
'importe' => $request->input("importe"),
'servicio_id' => $request->input("servicio_id"),
]);
return view('cobrar',compact('cobros', 'evento', 'servicio', 'event'))->with($data);
}
Image Database:
I suggest adding a check to see if method is get or post...
public function cobrar(Request $request,$id){
$data = [
'category_name' => 'datatable',
'page_name' => 'custom',
'has_scrollspy' => 0,
'scrollspy_offset' => '',
];
$cliente = \App\Models\Eventos::first();
$cobros = \App\Models\Cobros::where('turno_id', $request->id)->first();
$evento = \App\Models\Eventos::where('id' , $id)->with('servicio')->first();
$servicio = \App\Models\Servicios::where('id', $evento->servicio_id)->first();
$event = \App\Models\Eventos::find($id);
if ($request->isMethod('post')) {
Cobros::insert([
'turno_id' => $request->input("turno_id"),
'importe' => $request->input("importe"),
'servicio_id' => $request->input("servicio_id"),
]);
}
return view('cobrar',compact('cobros', 'evento', 'servicio', 'event'))->with($data);
}
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 working on multiple image uploads i got the problem that 1st image is uploading properly and for second image it shows out the file upload error attack
Can you help me to find out the problem
Controller
public function mimageAction()
{
$form = new MultipleImageForm();
$form->get('submit')->setValue('Submit');
$request = $this->getRequest();
if($request->isPost())
{
$nonFile = $request->getPost()->toArray();
$File = $this->params()->fromFiles('file');
$data = array_merge_recursive($request->getPost()->toArray(), $request->getFiles()->toArray());
//print_r($data); die;
$form->setData($data);
if ($form->isValid())
{
$count = count($data['varad']);
// $dataNew=array(
// 'test'=>trim($data['test']),
// 'file'=>trim($data['file']['name']),
// 'image'=>trim($data['image']['name'])
// );
$request = new Request();
$files = $request->getFiles();
for($i=0;$i<$count;$i++)
{
$adapter = new \Zend\File\Transfer\Adapter\Http();
$adapter->setDestination('public/img/upload/'); // Returns all known internal file information
//$adapter->addFilter('File\Rename', array('target' =>"public/img/upload" . DIRECTORY_SEPARATOR .$data['varad'][$i]['name'] , 'overwrite' => true));
$filter = new \Zend\Filter\File\RenameUpload("public/img/upload/");
$filter->filter($files['varad'][$i]['name']);
$filter->setUseUploadName(true);
$filter->filter($files['varad'][$i]['name']);
if(!$adapter->receive())
{
$messages = $adapter->getMessages();
print_r($messages);
}
else
{
echo "Image Uploaded";
}
}
// $adapter = new \Zend\File\Transfer\Adapter\Http();
// $adapter->setDestination('public/img/upload/'); // Returns all known internal file information
// $adapter->addFilter('File\Rename', array('target' =>"public/img/upload" . DIRECTORY_SEPARATOR .$image2, 'overwrite' => true));
//
// if(!$adapter->receive())
// {
// $messages = $adapter->getMessages();
// print_r($messages);
// }
// else
// {
// echo "Image Uploaded";
// }
}
}
return array('form' => $form);
}
Form
public function __construct($name = null)
{
parent::__construct('stall');
$this->setAttribute("method","post");
$this->setAttribute("enctype","multipart/form-data");
$this->add(array(
'name' => 'varad',
'attributes' => array(
'type' => 'file',
'multiple'=>'multiple',
),
'options' => array(
'label' => 'First Image',
),
'validators' => array(
'Size' => array('max' => 10*1024*1024),
)
));
$this->add(array(
'name' => 'test',
'attributes' => array(
'type' => 'text',
),
'options' => array(
'label' => 'Text Box',
),
));
$this->add(array(
'name' => 'varad',
'attributes' => array(
'type' => 'file',
'multiple'=>'multiple',
),
'options' => array(
'label' => 'Second Image',
),
));
$this->add(array(
'name' => 'submit',
'type' => 'submit',
));
}
Here i also tried by getting different names for images as well as different procedures for images
I think u can't use
$request->getFiles();
for this solution.
Please try to use $adapter->getFileInfo()
It's getting files from const _FILES.
I give my example for u:
$adapter = new Zend_File_Transfer_Adapter_Http();
$newInfoData = [];
$path = $this->getBannerDirByBannerId($banner->getId());
foreach ($adapter->getFileInfo() as $key => $fileInfo) {
if (!$fileInfo['name']) {
continue;
}
if (!$adapter->isValid($key)) {
return $this->getPartialErrorResult($adapter->getErrors(), $key);
}
$fileExtension = pathinfo($fileInfo['name'], PATHINFO_EXTENSION);
$newFileName = $key . '.' . $fileExtension;
if (!is_dir($path)) {
#mkdir($path, 0755, true);
}
$adapter->addFilter('Rename', array(
'target' => $path . $newFileName,
'overwrite' => true
));
$isReceive = $adapter->receive($key);
if ($isReceive) {
$newInfoData[$key] = $newFileName;
}
}
if (!empty($newInfoData)) {
$newInfoData['id'] = $banner->getId();
return BannerModel::getInstance()->updateBanner($newInfoData);
} else {
return new Model_Result();
}
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