Laravel Passport doesn't bring results in foreach loop sometimes - laravel

I'm trying to get data with laravel passport API, which returns null for some IDs in a foreach loop. But if I pick that Id and try to get individual results, it works fine. When we have 50 or more records, it starts to create problems.
Code Sample:
public function name()
{
set_time_limit(0);
ini_set('memory_limit', '-1');
try{
$all_product_prices = SProductNcrPadPrice::select('id', 'product_id', 'sku')->get();
if (!empty($all_product_prices)) {
foreach ($all_product_prices as $key => $row_signal_product_price) {
$ncr_token = $this->createNcrPadsToken();
$response_get_list = Http::withToken($ncr_token)->get($this->base_url.'/product/get_list?queryString={"product_id": "'.$row_signal_product_price->sku.'"}');
$products_list_get = json_decode($response_get_list->body(), true);
info($products_list_get);
if(!empty($products_list_get["data"]) && count($products_list_get["data"]) > 0){
echo "<pre>";
echo "In";
}else{
echo "<pre>";
echo "Out";
}
}
}
}catch(HttpEmptyResponse $e)
{
abort(500, 'contact support');
}
}

Related

Object of class Illuminate\Routing\Redirector could not be converted to string. srmklive/laravel-paypal

I am currently working on a paypal checkout using paypal and https://github.com/srmklive/laravel-paypal. I'm using the express checkout which I modified it a little bit to fit the requirements of the my project. During testing it is working in a couple of tries, paypal show and payment executes properly but when I tried to run the exact same code. I get this error I don't know what it means.
I tried to check my routes if it all of the errors happens to my routes but all of it are working properly. I also tried dump and die like dd("check") just to check if its really going to my controller and it does. I did this in the method "payCommission" (this where the I think the error happens)
This is my route for the controller
api.php
Route::get('service/commissionfee/payment' , 'api\service\ExpressPaymentController#payCommission');
Route::get('paypal/ec-checkout-success', 'api\service\ExpressPaymentController#payCommissionSuccess');
ExpressPaymentController.php
<?php
namespace App\Http\Controllers\api\service;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Srmklive\PayPal\Services\ExpressCheckout;
class ExpressPaymentController extends Controller
{
protected $provider;
public function __construct()
{
try {
$this->provider = new ExpressCheckout();
}
catch(\Exception $e){
dd($e);
}
}
public function payCommission(Request $request)
{
$recurring = false;
$cart = $this->getCheckoutData($recurring);
try {
$response = $this->provider->setExpressCheckout($cart, $recurring);
return redirect($response['paypal_link']);
} catch (\Exception $e) {
dd($e);
return response()->json(['code' => 'danger', 'message' => "Error processing PayPal payment"]);
}
}
public function payCommissionSuccess(Request $request)
{
$recurring = false;
$token = $request->get('token');
$PayerID = $request->get('PayerID');
$cart = $this->getCheckoutData($recurring);
// ? Verify Express Checkout Token
$response = $this->provider->getExpressCheckoutDetails($token);
if (in_array(strtoupper($response['ACK']), ['SUCCESS', 'SUCCESSWITHWARNING'])) {
if ($recurring === true) {
$response = $this->provider->createMonthlySubscription($response['TOKEN'], 9.99, $cart['subscription_desc']);
if (!empty($response['PROFILESTATUS']) && in_array($response['PROFILESTATUS'], ['ActiveProfile', 'PendingProfile'])) {
$status = 'Processed';
} else {
$status = 'Invalid';
}
} else {
// ? Perform transaction on PayPal
$payment_status = $this->provider->doExpressCheckoutPayment($cart, $token, $PayerID);
$status = $payment_status['PAYMENTINFO_0_PAYMENTSTATUS'];
}
return response()->json(['success' => "payment complete"]);
}
}
private function getCheckoutData($recurring = false)
{
$data = [];
$order_id = 1;
$data['items'] = [
[
'name' => 'Product 1',
'price' => 9.99,
'qty' => 1,
],
];
$data['return_url'] = url('api/paypal/ec-checkout-success');
// !
$data['invoice_id'] = config('paypal.invoice_prefix').'_'.$order_id;
$data['invoice_description'] = "Commission Fee payment";
$data['cancel_url'] = url('/');
$total = 0;
foreach ($data['items'] as $item) {
$total += $item['price'] * $item['qty'];
}
$data['total'] = $total;
return $data;
}
}
Error I am getting
Object of class Illuminate\Routing\Redirector could not be converted to string
Thank you in advance
you may just go to the config/paypal.php and edit
'invoice_prefix' => env('PAYPAL_INVOICE_PREFIX', 'Life_saver_'),
you may use _ underline in this like Life_saver_, dont forget use underline at the end too.

How to get the value of a variable from the collection

public function returnsTrueIfEmailIsVerified(Request $request)
{
// Gets the email
$email = request("email"); //johndoe#example.com for example
// Determine if zero or one ;
$user = User::where('email','=',$email)->get(); // 0 or 1 ;
$userCount = User::where('email','=',$email)->count(); // 0 or 1 ;
$confirmedValue = $user->get('confirmed');
$response ;
if ( $user === 1 && $confirmedValue === true ) {
$response = 'OK';
}
elseif ($user === 1 && $confirmedValue === false) {
$response = 'Not Confirmed yet';
}
else {
$response = 'Not Registered yet';
}
return response()->json(200,$response);
}
with that code I would return a response that if a user isn't registered or is registered and that if he's registered but that he's not confirmed yet..
I want to return something out from that I'm not just familiar with laravel's way
There are so many error in your code, I've fixed it and this code will work. I think you need to learn more Laravel and PHP.
public function returnsTrueIfEmailIsVerified(Request $request)
{
$email = request("email");
$user = User::where('email', '=', $email);
$response = [
'message' => ''
];
if ($user->count() === 1) {
$confirmedValue = $user->first()->confirmed;
if ($confirmedValue) {
$response['message'] = 'OK';
} else {
$response['message'] = 'Not Confirmed yet';
}
} else {
$response['message'] = 'Not Registered yet';
}
return response()->json($response, 200);
}
you can't response string as a json, json is key value pair.
User::where('email', '=', $email) return Query Builder not 0 or 1, use count() method;
you can't retrieve value from multiple items you have to specific item like this $user->get()[0]['confirmed] or use Laravel special method $user->first()->confirmed

Laravel: export searched data to the excel

I want to export searched data to the laravel below is my controller
public function getUsageData(Request $request)
{
$start_date = $request->get('start_date');
$end_date = $request->get('end_date');
$particulars = DB::table('particulars')
->join('reqs', 'particulars.particular_id', "=", 'reqs.particular_id')
->whereBetween('date_applied', [$start_date, $end_date])
->select('particulars.item_name', 'particulars.unit', 'particulars.price', 'reqs.quantity_issued',
DB::raw('particulars.price*reqs.quantity_issued AS total_cost'))
->get();
if ($particulars->isEmpty()) {
return "No Records Found...................... ";
} else {
$pdf = PDF::loadView('issuer.getUsageReport', ['particulars' => $particulars]);
return $pdf->stream('getUsageReport.issuer');
}
}
I want to retrieve those data to the excel instead of pdf please help
Replace the two PDF lines in the else { ... } statement with:
$list = $particulars->toArray();
//This line adds headers if present in your data
array_unshift($list, array_keys($list[0]));
$callback = function() use ($list) {
$FH = fopen('php://output', 'w');
foreach ($list as $row) {
fputcsv($FH, $row);
}
fclose($FH);
};
return response()->streamDownload($callback,"filename.csv");
Depending on the structure of particulars you may need to do some manipulation to the data first, e.g. flattening. Comment below if so.

how to check if username already exists in codeigniter my error

My controler cod is:
function register()
{
if(isset($_POST['register'])){
$this->form_validation->set_rules('username','Username','required');
$this->form_validation->set_rules('email','Email','required');
$this->form_validation->set_rules('password','Password','required');
//
if($this->form_validation->run () == true){
echo 'Form Validate';
$data = array(
'username'=>$_POST['username'],
'email'=>$_POST['email'],
'password'=>strtoupper(hash('whirlpool',$_POST['password']))
);
$this->db->insert('accounts',$data);
$this->load->model("usuarios_model");
if($this->usuarios_model->check_user_exist($data['username'])){
echo "already user exist";
}{
$this->db->insert('accounts',$data);
redirect("painel/index");
}
}
}
$this->load->view("painel/register");
}
[![enter image description here][2]][2]
It registers an user even though the username already exists.
Where is the mistake?
You can use is_unique rule in your form_validation library.
$this->form_validation->set_rules('username','Username','required|is_unique[table.column]');
You have mistake in your model in where condition it will be small later of username but you used Username.
use this code in your model.
function check_user_exist($username){
$this->db->wehre('username',$username);
$this-db->from('accounts');
$query= $this->db->get();
if($query->num_rows() > 0){
return true;
}else{
return false;
}
}
and also controller data insert after user check:
if($this->usuarios_model->check_user_exist($data['username'])){
echo "already user exist";
}{
$this->db->insert('accounts',$data);
redirect("painel/index");
}
You can easily achieve this using call_back function in validation. From Codeigniter Docs
Controller
function register() {
if ($this->input->post('register')) {
$this->form_validation->set_rules('username','Username','required|callback_checkUserName');
$this->form_validation->set_rules('email','Email','required');
$this->form_validation->set_rules('password','Password','required');
//
if ($this->form_validation->run() == true) {
$data = array(
'username '=> $this->input->post('username'),
'email' => $this->input->post('email'),
'password' => strtoupper(hash('whirlpool', $this->input->post('password')))
);
$this->db->insert('accounts',$data);
echo 'success';
exit();
} else {
echo validation_errors(); die; // check errors
}
}
$this->load->view("painel/register");
}
// call back validate function
function checkUserName($userName){
if ($this->usuarios_model->checkUserexist($userName) == false) {
return true;
} else {
$this->form_validation->set_message('checkUserName', 'This userName already exist!');
return false;
}
}
MODEL
function checkUserexist($userName) {
$this->db->where('username', $userName);
$this-db->from('accounts');
$query = $this->db->get();
if ($query->num_rows() > 0) {
return true;
}
return false;
}
This my code which I used in one of my projects replace the words with your code:
$this->form_validation->set_rules('companyname','Company Name','trim|required|callback_companyname_exist');
Here is above callback function:
function companyname_exist($str) {
$this->db->where('company_name', $str);
$this->db->where('user_type','Shop');
$prod = $this->db->get('grs_user');
if ($prod->row()) {
$this->form_validation->set_message('companyname_exist', 'This Company name is already Available.');
return FALSE;
} else
return TRUE;
}
You can used this for already register email check also.

codeigniter how to show data in functions

My model:
function get_data($id)
{
$this->db->select('id, Company, JobTitle');
$this->db->from('client_list');
$this->db->where('id', $id);
$query = $this->db->get();
return $query->result();
}
I want to get the the data from get_data(), is this the right way?
public function show_data( $id )
{
$data = $this->get_data($id);
echo '<tr>';
echo '<td>'.$data['Company'].'</td>';
echo '<td>'.$data['JobTitle'].'</td>';
echo '<td>'.$data['id'].'</td>';
echo '<td></td>';
echo '</tr>';
}
Use the row_array() function to get the data in the array format.
Reference url
http://ellislab.com/codeigniter/user-guide/database/results.html
you can use foreach loop to print
foreach ($data->result() as $row)
{
echo '<tr>';
echo '<td>'.$row['Company'].'</td>';
echo '<td>'.$row['JobTitle'].'</td>';
echo '<td>'.$row['id'].'</td>';
echo '<td></td>';
echo '</tr>';
}
thank you
just to improve answer, I use "general_model" for all my controllers, there are some exceptions where I need special queries, I just create desired model so "general_model" stays same and I can use it in any project.
e.g.
general_model.php
function _getWhere($table = 'table', $select = 'id, name', $where = array()) {
$this->db->select($select);
$q = $this->db->get_where('`'.$table.'`', $where);
return ($q->num_rows() > 0) ? $q->result() : FALSE;
}
.
.
.
//bunch of another functions
in controller I just call
$this->data['books'] = $this->general_model->_getWhere('book', '*', array('active' => '1'));
$this->render('book_list_view'); // $this->load->view('book_list_view', $this->data);
sidenote: I am extending CI_Controller therefore I use $this->data['books'] instead $data['books'] to pass data into view
in view
//check if there are any data
if ($books === FALSE) {
//some error that there are no books yet
} else {
//load data to table or something
foreach ($books as $book) {
$book->id; // book id
}
}

Resources