Trying to get property of non-object - laravel - laravel

I am tring to do now is to make a many to many relation between "payments" table and "invoices" table ... but my problem is when i try to add a new payment and i select e list of invoices laravel gives me " Trying to get property of non-object " in line 217 ..
this is my code :
$selectedInvoices = $input['invoice'];
$invoices = collect([]);
foreach ($selectedInvoices as $invoice) {
$invoices = $invoices->merge([Invoice::find(Invoice::getPrivateId($invoice))]);
}
$invoices->all();
$invoices = $invoices->sortByDesc(function($invoice)
{
return $invoice->invoice_date;
});
$invoices->values()->all();
$totalAmount = 0;
foreach ($invoices as $invoice)
{
$totalAmount = $totalAmount + $invoice->balance;
}
if($payment->amount > $totalAmount){
foreach ($invoices as $invoice){
$adjustment = $invoice->balance * -1;
$partial = max(0, $invoice->partial - 0);
$invoice->updateBalances($adjustment, $partial);
$invoice->updatePaidStatus();
$payment->invoices()->attach($invoice->id) ;
}
$credit = Credit::createNew();
$credit->client_id = $clientId;
$credit->amount = $payment->amount - $totalAmount ;
$credit->balance = $payment->amount - $totalAmount ;
$credit->credit_date = $payment->payment_date;
$credit->private_notes = 'Crédit créé automatiquement suite au payement '.$payment->id.
' avec un montant de '.$payment->amount.' à la date de '.$payment->payment_date;
$credit->save();
}
if($payment->amount <= $totalAmount)
{
/*line 217*/ while ($payment->amount >= $invoices->last()->balance){
$payment->amount = $payment->amount - $invoices->last()->balance ;
$adjustment = $invoices->last()->balance * -1;
$partial = max(0, $invoices->last()->partial - 0);
$invoices->last()->updateBalances($adjustment, $partial);
$invoices->last()->updatePaidStatus();
$payment->invoices()->attach($invoices->last()->id) ;
$invoices->pop();
$invoices->all();
}
if ($payment->amount < $invoices->last()->balance){
$adjustment = $payment->amount * -1;
$partial = max(0, $invoices->last()->partial - $payment->amount);
$invoices->last()->updateBalances($adjustment, $partial);
$invoices->last()->updatePaidStatus();
$payment->invoices()->attach($invoices->last()->id) ;
}
}
p.s: when i give an amount > total amount of my invoices it works also when i give an amount < total amount it works too ..

Switch line 217
From:
while ($payment->amount >= $invoices->last()->balance){
To:
while (count($invoices) && $payment->amount >= $invoices->last()->balance) {
Explanation: $invoices->pop() is removing the last item in the collection. When all the items have been removed from the invoices collection, no invoice object will be found; Hence, the Trying to get property of non-object

Related

Referral link share and earn money up to 5 levels reward goes according to the level

here is the page joining methods and level
let me details you proper, let a person name A joined directly without any referral and buy a membership then A person share referral link to person B, B person joined on behalf of the person A, A person get reward to directly joined B person, person A level is A then the person B share his referral link to the person C, on joining C person buy membership. Person A get reward of 2 level and Person B get reward of level 1 then person C share referral link to person D then person A's level will be 3 and person B level 2 person C level 1 then person – D share referral to person E then A level will be 4 and person B level 3, person C 2 , person D 1 etc so On and if the level of A will be 6 didn't get any reward of the recently upper level join person mean 5th person to the tree and other person except A will get reward according –I can only achieve every last 5 level person records on new person joining using recursively call the function name check_level()
[enter image description here][1]
[enter image description here][2]
[enter image description here][3]
[enter image description here][4]
[1]: https://i.stack.imgur.com/5oLOI.png
[2]: https://i.stack.imgur.com/xuvkc.png
[3]: https://i.stack.imgur.com/IyCSk.png
[4]: https://i.stack.imgur.com/N5ZUs.png
//here is the code
function check_level($user, $level, $subscribed_package = null) //recusive calling function
{
$level = $level;
$check_directs = 0;
$check_points = 0;
$user = $user;
$user_reward = null;
$subscribed_package = $subscribed_package; // new purchased package
$newReferrar = new Referral(); // inserting referal record to reward
// $package = Subscription::where('user_id', $user->id)->where('payment', 'paid')->latest()->first(); // checking user packages
// $package_level = Package::findOrFail($package->package_id);// max package level
$directReward = User::where('my_referral', $user->refer_by)->first(); // who refer directly
if (!blank($directReward)) {
$user_package = Subscription::where('user_id', $directReward->id)->where('payment', 'paid')->latest()->first(); // check referer package level
$user_package = Package::findOrFail($user_package->package_id); // max package level
if ($level <= ($user_package->level )) { //comparing level
$newReferrar->user_id = $directReward->id; // put refer id
$newReferrar->user_refer_by = $directReward->refer_by; // who referrer to refer direct
$newReferrar->level_user_id = $user->my_referral; //
$newReferrar->level_no = $level;
$newReferrar->points = 8;
if ($level == 1) {
$newReferrar->direct = 1;
}
if ($level == 1) {
$newReferrar->reward = (40 * $subscribed_package->bv);
} elseif ($level == 2) {
$newReferrar->reward = (10 * $subscribed_package->bv);
} else {
$newReferrar->reward = (5 * $subscribed_package->bv);
}
// return $newReferrar;
$newReferrar->save();
$level = $level + 1;
$refer_by = $newReferrar->user_refer_by; // next level id finder
$check_directs = Referral::where('user_id', $newReferrar->user_id)->sum('direct'); // direct team sum
$check_points = Referral::where('user_id', $newReferrar->user_id)->sum('points'); // team points sum
$user_reward = new UserReward();
if (($check_directs >= 8 && $check_directs < 16) && ($check_points>= 320 && $check_points < 800)) { $check_bronze_user=UserReward::where('user_id', $newReferrar->user_id)->where('rank', 'Bronze')->first();
if (blank($check_bronze_user)) {
$user_reward->user_id = $newReferrar->user_id;
$user_reward->referral_id = $newReferrar->id;
$user_reward->rewards = 2000;
$user_reward->rank = 'Bronze';
$user_reward->direct = $check_directs;
$user_reward->points = $check_points;
$user_reward->save();
}
} elseif (($check_directs >= 16 && $check_directs < 30) && ($check_points>= 800 && $check_points < 2000)) { $check_silver_user=UserReward::where('user_id', $newReferrar->user_id)->where('rank', 'Silver')->first();
if (blank($check_silver_user)) {
$user_reward->user_id = $newReferrar->user_id;
$user_reward->referral_id = $newReferrar->id;
$user_reward->rewards = 5000;
$user_reward->rank = 'Silver';
$user_reward->direct = $check_directs;
$user_reward->points = $check_points;
$user_reward->save();
}
} elseif ($check_directs >= 30 && ($check_points >= 2000 && $check_points < 7200)) { $check_gold_user=UserReward::where('user_id', $newReferrar->user_id)->where('rank', 'Gold')->first();
if (blank($check_gold_user)) {
$user_reward->user_id = $newReferrar->user_id;
$user_reward->referral_id = $newReferrar->id;
$user_reward->rewards = 15000;
$user_reward->rank = 'Gold';
$user_reward->direct = $check_directs;
$user_reward->points = $check_points;
$user_reward->save();
}
} elseif ($check_points >= 7200 && $check_points < 21600) { $check_platinum_user=UserReward::where('user_id', $newReferrar->user_id)->where('rank', 'Platinum')->first();
if (blank($check_platinum_user)) {
$check_refer_by = Referral::where('user_refer_by', $directReward->my_referral)->pluck('user_id');
$golden_counter = UserReward::whereIn('user_id', $check_refer_by)->where('rank', 'Gold')->count();
// $golden_counter = 0;
// foreach ($check_gold as $gold) {
// if ($gold->rank == 'Gold') {
// $golden_counter++;
// }
// }
if ($golden_counter >= 2) {
$user_reward->user_id = $newReferrar->user_id;
$user_reward->referral_id = $newReferrar->id;
$user_reward->rewards = 30000;
$user_reward->rank = 'Platinum';
$user_reward->direct = $check_directs;
$user_reward->points = $check_points;
$user_reward->save();
}
}
} elseif ($check_points >= 21600 && $check_points < 86400) { $check_diamond_user=UserReward::where('user_id', $newReferrar->user_id)->where('rank', 'Diamond')->first();
if (blank($check_diamond_user)) {
$check_refer_by = Referral::where('user_refer_by', $directReward->my_referral)->pluck('user_id');
$platinum_counter= UserReward::whereIn('user_id', $check_refer_by)->where('rank', 'Platinum')->count();
// $platinum_counter = 0;
// foreach ($check_platinum as $gold) {
// if ($gold->rank == 'Platinum') {
// $platinum_counter++;
// }
// }
if ($platinum_counter >= 2) {
$user_reward->user_id = $newReferrar->user_id;
$user_reward->referral_id = $newReferrar->id;
$user_reward->rewards = 50000;
$user_reward->rank = 'Diamond';
$user_reward->direct = $check_directs;
$user_reward->points = $check_points;
$user_reward->save();
}
}
} elseif ($check_points >= 86400 && $check_points < 345600) { $check_blue_diamond_user=UserReward::where('user_id', $newReferrar->user_id)->where('rank', 'Blue Diamond')->first();
if (blank($check_blue_diamond_user)) {
$check_refer_by = Referral::where('user_refer_by', $directReward->my_referral)->pluck('user_id');
$diamond_counter = UserReward::whereIn('user_id', $check_refer_by)->where('rank', 'Diamond')->count();
// foreach ($check_Diamond as $gold) {
// if ($gold->rank == 'Diamond') {
// $diamond_counter++;
// }
// }
if ($diamond_counter >= 3) {
$user_reward->user_id = $newReferrar->user_id;
$user_reward->referral_id = $newReferrar->id;
$user_reward->rewards = 75000;
$user_reward->rank = 'Blue Diamond';
$user_reward->direct = $check_directs;
$user_reward->points = $check_points;
$user_reward->save();
}
}
} elseif ($check_points >= 345600) {
$check_black_diamond_user = UserReward::where('user_id', $newReferrar->user_id)->where('rank', 'Black Diamond')->first();
if (blank($check_black_diamond_user)) {
$check_refer_by = Referral::where('user_refer_by', $directReward->my_referral)->pluck('user_id');
$blue_diamond_counter = UserReward::whereIn('user_id', $check_refer_by)->where('rank', 'Blue Diamond')->count();
// foreach ($check_blue_diamond as $gold) {
// if ($gold->rank == 'Blue Diamond') {
// $blue_diamond_counter++;
// }
// }
if ($blue_diamond_counter >= 3) {
$user_reward->user_id = $newReferrar->user_id;
$user_reward->referral_id = $newReferrar->id;
$user_reward->rewards = 150000;
$user_reward->rank = 'Black Diamond';
$user_reward->direct = $check_directs;
$user_reward->points = $check_points;
$user_reward->save();
}
}
}
if ($refer_by != null) {
$user = User::where('refer_by', $refer_by)->first();
if (!blank($user)) {
check_level($user, $level, $subscribed_package);
}
}
}
}
}

Laravel foreach not working into my product multiiple discount model?

I have build discount system based on product and user id, I have almost done everything i just got error in my laravel model bellow my code:
public static function discount($p_id)
{
$discount = Discount::where('user_id', Auth::user()->id )->first();
$p = Product::where('id', $p_id)->first();
$multidiscount = MultipleDiscount::where('user_id','like','%'.trim(Auth::user()->id).'%')->with('typeItems')->first();
$orderdetail = MultiDiscountType::where('multidiscount_id',$multidiscount->id)->pluck('value');
if( !is_null($multidiscount) || is_null($discount) ){
foreach ($multidiscount->typeItems as $key => $mdiscount) {
# code...
$discprice = explode(',', $orderdetail);
if( $discount->value <= $mdiscount->value ){
if( $mdiscount->type == 'percentage' ){
$p_val = $p->price / 100 * $mdiscount->value ;
$p_price = $p->price - $p_val;
}
}else{
if( $discount->type == 'percentage' ){
$p_val = $p->price / 100 * $discount->value;
$p_price = $p->price - $p_val;
}
else {
$p_val = $p->price - $discount->value;
$p_price = $p_val;
}
}
}
}
else {
$p_price = $p->price;
}
return $p_price;
}
I got nice result in my product blade view file but issue with in my multidiscount table have two rows but i get only last row value. Whats is the wrong i dont know bellow multiplediscount table structure:
Multi Discount Table:
|id| name |status |user_id|
|1 |Black Friday| active| 2, 3 |
I used repeater field for multiple discount based on product and user.
Multi Discount Table Item
|id| product it |value|discount_id|
|1 | 3 | 25 | 1 |
|2 | 2 | 20 | 1 |
Use get() instead of first() in your MultipleDiscount module to fetch all records:
$multidiscount = MultipleDiscount::where('user_id','like','%'.trim(Auth::user()->id).'%')->with('typeItems')->get();
Although I'm not sure why you are fetching the discounts for a specific user with the LIKE clause. For example, if you have a user with the ID of 10, this will return values for the users with the ID that somehow contains 10 like 1101, 1210212, ... and so on.
EDIT:
foreach ($multidiscount as $key => $mdiscount) {
# code...
$discprice = explode(',', $orderdetail);
if( $discount->value <= $mdiscount->typeItems->value ){
if( $mdiscount->typeItems->type == 'percentage' ){
$p_val = $p->price / 100 * $mdiscount->typeItems->value ;
$p_price = $p->price - $p_val;
}
}else{
if( $discount->type == 'percentage' ){
$p_val = $p->price / 100 * $discount->value;
$p_price = $p->price - $p_val;
}
else {
$p_val = $p->price - $discount->value;
$p_price = $p_val;
}
}
}

issue with reduce time to open in laravel

I am making a report in which user can check due balance of them invoice day wise like between 1-30 days how many amount due. between 30-60 days how many amount due etc for that I have make below function.
I don't know how can I optimize this process time.
public function yajraAgingARSummaryByDueDate()
{
$customerData = GenerateInvoice::select('orders.customer_id','customers.first_name', 'customers.last_name','customers.terms','customers.account_id','customers.account_suffix','invoice.due_date','invoice.invoice_number')
->leftJoin('orders','orders.id','=','invoice.order_id')
->leftJoin('customers', 'customers.id', 'orders.customer_id')
->whereDate('invoice.due_date','<=',date('Y-m-d'))
->whereNotNull('orders.customer_id')
->where('invoice.is_invoice_paid','=','no')
->whereNull('invoice.deleted_at')
->groupBy('orders.customer_id')
->get();
$resultArr = [];
if(count($customerData))
{
foreach($customerData as $key => $row)
{
$current = 0;
$b_1_30 = 0;
$b_31_60 = 0;
$b_61_90 = 0;
$b_over_90 = 0;
$total_ar = 0;
$balance = 0;
$invoiceData = GenerateInvoice::select('invoice.id')
->leftJoin('orders','orders.id','=','invoice.order_id')
->where('orders.customer_id',$row['customer_id'])
->whereDate('invoice.due_date','<=',date('Y-m-d'))
->whereNotNull('orders.customer_id')
->whereNull('invoice.deleted_at')
->where('invoice.is_invoice_paid','=','no')
->get();
if(count($invoiceData))
{
foreach($invoiceData as $row1)
{
$data = GenerateInvoice::select(DB::raw("abs(DATEDIFF(STR_TO_DATE(due_date, '%Y-%m-%d'),CURDATE())) AS Days"),'orders.total_order_value','payments.payment_amount')
->selectRaw(' (select sum(auto_cash_distributions.payment_amount) from auto_cash_distributions where auto_cash_distributions.order_id = invoice.order_id and payment_amount is not null ) as acd_payament_amount ')
->leftJoin('orders','orders.id','=','invoice.order_id')
->leftJoin('payments','payments.order_id','=','orders.id')
->where('invoice.id',$row1['id'])
->whereNotNull('orders.customer_id')
->whereNull('invoice.deleted_at')
->whereNull('payments.deleted_at')
->where('invoice.is_invoice_paid','=','no')
// ->groupBy('payments.invoice_id')
->first();
$days = $data['Days'];
$acd_payament_amount = !(empty($data['acd_payament_amount'])) ? $data['acd_payament_amount'] : 0;
$payment_amount = $data['payment_amount'] + $acd_payament_amount;
$amount = $data['total_order_value'] - $payment_amount;
// H 30/12
$amount = $amount;
$balance =$balance + $amount;
$total_ar = $total_ar + $amount;
// $total_ar = $amount;
if($days>90)
{
$b_over_90 = $b_over_90 + $amount;
}
else if($days <=90 && $days>=61)
{
$b_61_90 = $b_61_90 + $amount;
}
else if($days <=60 && $days>=31)
{
$b_31_60 = $b_31_60 + $amount;
}
else if($days <=30 && $days>=1)
{
$b_1_30 = $b_1_30 + $amount;
}
else
{
$current = $current + $amount;
}
}
}
$resultArr[$key]['account_id'] = $row['account_id'];
$resultArr[$key]['account_suffix'] = $row['account_suffix'];
$resultArr[$key]['first_name'] = $row['first_name'];
$resultArr[$key]['terms'] = $row['terms'];
$resultArr[$key]['due_date'] = $row['due_date'];
$resultArr[$key]['invoice_number'] = $row['invoice_number'];
$resultArr[$key]['balance'] = number_format($balance,2,'.','');
$resultArr[$key]['current'] = number_format($current,2,'.','');
$resultArr[$key]['b_1_30'] = number_format($b_1_30,2,'.','');
$resultArr[$key]['b_31_60'] = number_format($b_31_60,2,'.','');
$resultArr[$key]['b_61_90'] = number_format($b_61_90,2,'.','');
$resultArr[$key]['b_over_90'] = number_format($b_over_90,2,'.','');
$resultArr[$key]['total_ar'] = number_format($total_ar,2,'.','');
}
}
return Datatables::of($resultArr)
->addColumn('due_date',function($sql){
return !empty($sql['due_date']) ? date(get_config('date_format'),strtotime($sql['due_date'])) : '';
})
->addIndexColumn()
->rawColumns(['due_date'])
->make(true);
}
but this code is taking to much time to open. can anybody help me to optimize this code?

How to pluck a value from foreach statement in Laravel

I am getting an array from database table and through a for each statement. Then check the difference between two values if there is any difference that is less than zero sets a value to 0 for that loop. Then do the same with the next loop.
$bom_id = App\Models\Bom::where('item_id', $item->order_item->id)->pluck('id')->first();
if ($bom_id > 0) {
$bomList = App\Models\Bom_list::where('bom_id', $bom_id)->get();
echo '<div class="row">';
foreach ($bomList as $bomlist) {
$availableQty = $item->order_item->qty;
$requiredQty = $bomlist->qty * $item->qty;
$dif = $availableQty - $requiredQty;
}
$check = '';
$arr = array($bomlist->$dif);
$light = in_array($check, $arr, true) ? 0 : 1;
} else {
$light = 0;
}
enter image description here

cakephp 3 inserting data in other controller .. but data not getting saved and returned no errors

Here is my code
PurchaseDetails from another model
inserting data in this table called PurchaseDetails
$purchaseobjev = TableRegistry::get('PurchaseDetails'); // other model
$PDvari = $purchaseobjev->newEntity();
$PDvari->purchase_origins_id = 11;
$PDvari->product_codes_id = 1;
$PDvari->store_lists_id =1;
$PDvari->hand_types_idsss =1;
$PDvari->core_pattern =1;
$PDvari->color_list =1;
$PDvari->measurement_types_id = 1;
$PDvari->measurement_inventories_id = 1;
$PDvari->measurement_value =1;
$PDvari->measurement_total =1;
$PDvari->price_range = 1;
if( $purchaseobjevs->save($PDvari) ) {
echo "here";die;
}else{
echo "no";die;
}
$PDvari = array_values($PDvari);
$articles = TableRegistry::get('PurchaseDetails');
$entities = $articles->newEntities($PDvari);
foreach ($entities as $entity) {
$maxId = $articles->save($entity);
}

Resources