My current situation is: I must use save() method to save multiple records using loop. I know insert() will fix my problem but to maintain my code clean I have to use the same code and save() method to insert the record. I create new instance inside the loop but always only last record is being inserted. My code looks like:
public static function save($data)
{
$settings = Settings::instance();
$data['sender_address'] = urldecode($data['sender_address']);
$data['sender_address'] = json_decode($data['sender_address'], true);
extract($data);
$customerFields = ['name', 'mobile', 'alt_mobile', 'district_id', 'area_id', 'address'];
$customerObj = $customer = Customer::where('mobile', $mobile);
if ($customerObj->count()) {
$customer = $customer->first();
} else {
$customer = new Customer;
}
foreach ($customerFields as $customerField) {
if (!empty($$customerField)) {
$customer->$customerField = $$customerField;
}
}
($customerObj->count()) ? $customer->update() : $customer->save();
$order = (isset($order_id) && !empty($order_id) )? Order::find($order_id) : new Order;
$order->sender_address = $sender_address;
$order->branch_id = self::getBranchIdByAreaId($sender_address['area']);
$order->responsible_by = self::getBranchManagerIdByBranchId($order->branch_id);
$order->client_id = $client_id;
$order->customer_id = $customer->id;
$order->delivery_time = $delivery_time;
$deliveryChargeParams = [
'district_id' => $district_id,
'delivery_time' => $delivery_time,
'product_weight' => $product_weight,
'merchant_id' => $client_id,
];
$order->delivery_charge = Utility::getDeliveryCharge($deliveryChargeParams);
$order->vat = Utility::getVat($order->delivery_charge);
if (empty($order_id)) {
$order->status_id = ($role_id == Employee::CLIENT) ?
$settings['tracking']['default_status'] : Order::PACKAGINGDONE;
if (($role_id != Employee::CLIENT)) {
$order->requested = Order::PACKAGINGDONE;
}
}
$order->cash_amount = $cash_amount;
$order->cod_charge = Utility::getCodCharge($cash_amount);
$order->product_weight = $product_weight;
$order->client_reference = $client_reference;
if (empty($order_id)) {
$order->save();
$loggedInUserId = isset($data['fromApp'])?
$data['client_id'] : Auth::getUser()->id;
$order->number = self::orderNumber($order,$loggedInUserId);
$order->update();
} else {
$order->update();
}
if (($role_id != Employee::CLIENT)) {
self::updateDeliveryWithin($order);
}
PaymentAction::update($order);
}
The following method calls this save() method:
function onSave(){
$data = post();
$client_id = (Auth::getUser()->role_id == Employee::CLIENT) ? Auth::getUser()->id : $data['client_id'];
$sender_address = $data['sender_address'];
$file = Input::file('bulk_order');
$filename = time().'-'.rand(2000,99999999).'-'.$file->getClientOriginalName();
$result = $file->move('tempFiles',$filename);
$uploadedFilePath = 'tempFiles/'.$filename;
$contents = $this->csvToArray($uploadedFilePath);
// dd($contents); //exit;
unlink($uploadedFilePath);
$keys = array();
if(count($contents)){
$keys = array_keys($contents[0]);
}else{
throw new ApplicationException('Your Csv file is not in proper Format OR Empty!');
}
$fields = array('client_reference','customer_mobile','customer_alternative_mobile','customer_name','customer_district','customer_area','customer_address','product_weight_in_kg','delivery_time_in_hour','cash_collection');
$diff = array_diff($keys,$fields);
//dd($diff); exit;
if(count($diff)!=0){
throw new ApplicationException('Your Csv file is not in proper Format');
}
// dd($contents); exit;
foreach($contents as $row){
$data['name'] = $row['customer_name'];
$data['mobile'] = $row['customer_mobile'];
if(strlen($data['mobile']) == 10 ){
$data['mobile'] = '0'.$data['mobile'];
}
$data['alt_mobile'] = $row['customer_alternative_mobile'];
if(strlen($data['alt_mobile']) == 10 ){
$data['alt_mobile'] = '0'.$data['alt_mobile'];
}
$data['district_id'] = Utility::getDistrictIdByName($row['customer_district']);
$data['area_id'] = Utility::getAreaIdByName($row['customer_area']);
$data['address'] = $row['customer_address'];
$data['delivery_time'] = $row['delivery_time_in_hour'];
$data['product_weight'] = $row['product_weight_in_kg'];
$data['client_id'] = $client_id;
$data['sender_address'] = $sender_address;
$data['cash_amount'] = $row['cash_collection'];
$data['client_reference'] = $row['client_reference'];
$data['role_id'] = Auth::getUser()->role_id;
OrderAction::save($data);
}
\Flash::success('Bulk Order uploaded Successfully');
return Redirect::to('dashboard/shipments');
}
Is it possible to save multiple records with my approach? Thanks in advance.
Related
When i try to log mikrotik users activity we understood mikrotik assign another id to online users than when we created user with /ip/hotspot/user/add command, is there any solution to find which user connected to internet in mikrotik?
class MikrotikLoggerListener extends Command
{
protected $signature = 'mikrotik:logger';
protected $description = 'Mikrotik logger listener';
public function handle()
{
$users = User::all();
foreach ($users as $user) {
if ($user->log == 1) {
try {
$addRequest = new RouterOS\Request('/log print');
$result = (new RouterOS\Client($user->mikrotik_ip, $user->mikrotik_user, $user->mikrotik_password))->sendSync($addRequest);
foreach ($result as $object) {
$id = $object->getProperty('.id');
$time = $object->getProperty('time');
$topics = $object->getProperty('topics');
$message = $object->getProperty('message');
$exists = LogTemp::where('time','=',$time)->first();
if(!$exists) {
if (str_contains($message, 'logged out') || str_contains($message, 'disconnected')) {
$status = 'logged out';
$log = new LogTemp;
$log->user_id = $user->id;
$log->mikrotik_id = $id;
$log->time = $time;
$log->topics = $topics;
$log->message = $message;
$log->status = $status;
$log->save();
}
}
}
//--------------------------------------------------------------------------------------------------
$request = new RouterOS\Request('/ip/hotspot/active/print');
$router = new RouterOS\Client($user->mikrotik_ip, $user->mikrotik_user, $user->mikrotik_password);
$onlineUsers = $router->sendSync($request);
$count = $onlineUsers->count();
$this->info('customer: ' . $user->id . ' count: ' . $count);
for ($i = 0; $i < $count; $i++) {
if ($onlineUsers[$i]->getProperty('.id') != null) {
$mikrotik_id = $onlineUsers[$i]->getProperty('.id');
$current_user = LogTemp::where('user', '=', $onlineUsers[$i]->getProperty('user'))->first();
if ($current_user) {
$log = new LogTemp;
$log->user_id = $user->id;
$log->mikrotik_id = $mikrotik_id;
$log->user = $onlineUsers[$i]->getProperty('user') ?? '';
$log->address = $onlineUsers[$i]->getProperty('address') ?? '';
$log->mac_address = $onlineUsers[$i]->getProperty('mac-address') ?? '';
$log->login_by = $onlineUsers[$i]->getProperty('login-by') ?? '';
$log->bytes_in = $onlineUsers[$i]->getProperty('bytes-in') ?? '';
$log->bytes_out = $onlineUsers[$i]->getProperty('bytes-out') ?? '';
$log->packets_in = $onlineUsers[$i]->getProperty('packets-in') ?? '';
$log->packets_out = $onlineUsers[$i]->getProperty('packets-out') ?? '';
$log->status = 'online';
$log->save();
} else {
$log = new LogTemp();
$log->user_id = $user->id;
$log->mikrotik_id = $mikrotik_id;
$log->user = $onlineUsers[$i]->getProperty('user') ?? '';
$log->address = $onlineUsers[$i]->getProperty('address') ?? '';
$log->mac_address = $onlineUsers[$i]->getProperty('mac-address') ?? '';
$log->login_by = $onlineUsers[$i]->getProperty('login-by') ?? '';
$log->bytes_in = $onlineUsers[$i]->getProperty('bytes-in') ?? '';
$log->bytes_out = $onlineUsers[$i]->getProperty('bytes-out') ?? '';
$log->packets_in = $onlineUsers[$i]->getProperty('packets-in') ?? '';
$log->packets_out = $onlineUsers[$i]->getProperty('packets-out') ?? '';
$log->status = 'logged-in';
$log->save();
}
}
}
} catch (Exception $ignore) {
$this->info(' ->' . $ignore->getMessage());
}
try {
$addRequest = new RouterOS\Request('/log print');
$result = (new RouterOS\Client($user->mikrotik_ip, $user->mikrotik_user, $user->mikrotik_password))->sendSync($addRequest);
foreach ($result as $object) {
$message = $object->getProperty('message');
$mikrotik_id = $object->getProperty('.id');
if (str_contains($message, 'logged out') || str_contains($message, 'disconnected')) {
$current_user = LogTemp::where('user', '=', $mikrotik_id)->orderBy('id', 'DESC')->first();
if ($current_user) {
//dd($current_user);
$result = LogTemp::with('user')
->select([DB::raw('SUM(bytes_in) as download , SUM(bytes_out) as upload')])
->where('mikrotik_id','=',$mikrotik_id)
->groupBy('mikrotik_id')
->get();
$new_log = new UserConnectionsLog();
$new_log->user_id = $current_user->id;
$new_log->mikrotik_id = $current_user->mikrotik_id;
$new_log->user = $current_user->user;
$new_log->address = $current_user->address;
$new_log->mac_address = $current_user->mac_address;
$new_log->login_by = $current_user->login_by;
$new_log->bytes_in = $result['download'];
$new_log->bytes_out = $result['upload'];
$new_log->logged_in = $current_user->logged_in;
$new_log->logged_out = now();
//$new_log->save();
//LogTemp::where('mikrotik_id', '', $log->user)->delete();
}
}
}
} catch (Exception $ignore) {
$this->info('Log section error ->' . $ignore->getMessage());
}
}
}
}
}
I am using paypal integration in my web application everything is working fine . Checkout is working properly but when i apply the coupon then the paypal throws the exception of 400 error. Below is my code
I am using the daryldecode/cart for the checkout. The only problem is when I apply the coupon and move forward towards the paypal
public function paywithPaypal(Request $request)
{
// dd($request->all());
if(Auth::guest()){
if(Session::has('user_id')){
$sessionUserId = Session::get('user_id');
echo $sessionUserId;
}
$checkEmail= User::where('email',$request->billing_email )->first();
if(empty($checkEmail)) {
$user = User::create( [
'first_name' => $request->billing_first_name,
'last_name' => $request->billing_last_name,
'email' => $request->billing_email,
'username' => $request->billing_first_name,
'password' => bcrypt( 123456 ),
'province' => $request->billing_state,
'city' => $request->billing_town,
'address' => $request->billing_address_1,
'role' => 'Member',
] );
$userId = $user->id;
}else{
$userId = $checkEmail->id;
}
}else{
//user login
$sessionUserId = $userId = Auth::user()->id;
}
$items = [];
\Cart::session($sessionUserId)->getContent()->each(function($item) use (&$items)
{
$items[] = $item;
});
$subtotal = \Cart::session($sessionUserId)->getSubTotal();
// dd($subtotal);
$line1 = $request->billing_address_1;
$line2 = $request->billing_address_2;
$fullname = $request->billing_first_name ." ". $request->billing_last_name;
$state = $request->billing_state;
$zip = $request->billing_zip;
$phone = $request->billing_phone;
$email = $request->billing_email;
$city = $request->billing_town;
//invoke new order
$order = new Orders ;
$order->id = $order->generateID('INV');
$saved_order_id = $order->id;
$shippingAddress= Paypalpayment::shippingAddress();
$shippingAddress->setLine1($line1)
->setLine2($line2)
->setCity($city)
->setState($state)
->setPostalCode($zip)
->setCountryCode("US")
->setPhone($phone)
->setRecipientName($fullname);
// ### Payer
// A resource representing a Payer that funds a payment
// Use the List of `FundingInstrument` and the Payment Method
// as 'credit_card'
$payer = Paypalpayment::payer();
$payer->setPaymentMethod("paypal");
$listitem = array();
$fees=HandlingFee::find(1);
$fee = $fees->fee;
$shipping = $request->shipping_fee;
foreach($items as $key=>$item){
$listitem[$key] = Paypalpayment::item();
$listitem[$key]->setName($item->name)
->setCurrency('USD')
->setQuantity($item->quantity)
->setPrice($item->price);
$item_detail = new Order_Item_Details;
$item_detail->order_id = $saved_order_id;
$item_detail->item_id = $item->id;
$item_detail->qty = $item->quantity;
$item_detail->save();
}
$itemList = Paypalpayment::itemList();
$itemList->setItems($listitem)
->setShippingAddress($shippingAddress);
$details = Paypalpayment::details();
$details->setShipping($shipping)
->setHandlingFee($fee)
//total of items prices
->setSubtotal($subtotal);
$grandTotal = $subtotal + $fee + $shipping;
//dd($grandTotal);
//Payment Amount
$amount = Paypalpayment::amount();
$amount->setCurrency("USD")
// the total is $17.8 = (16 + 0.6) * 1 ( of quantity) + 1.2 ( of Shipping).
->setTotal($grandTotal)
->setDetails($details);
//dd($amount);
// ### Transaction
// A transaction defines the contract of a
// payment - what is the payment for and who
// is fulfilling it. Transaction is created with
// a `Payee` and `Amount` types
$transaction = Paypalpayment::transaction();
$transaction->setAmount($amount)
->setItemList($itemList)
->setDescription("Payment description")
->setInvoiceNumber($saved_order_id)
->setCustom($request->shipping_service);
// dd($transaction);
// ### Payment
// A Payment Resource; create one using
// the above types and intent as 'sale'
$redirectUrls = Paypalpayment::redirectUrls();
$redirectUrls->setReturnUrl(url("/payments/success"))
->setCancelUrl(url("/payments/fails"));
$payment = Paypalpayment::payment();
$payment->setIntent("sale")
->setPayer($payer)
->setRedirectUrls($redirectUrls)
->setTransactions([$transaction]);
$order->status = 1;
$order->user_id = $userId;
$order->total = $grandTotal;
$order->subtotal = $subtotal;
$order->shipping = $shipping;
if($request->coupon_code == ""){
$order->isCoupon = 0;
}
else{
$order->isCoupon = 1;
}
$order->isBillingDetail = 1;
if($request->shipping_first_name <> ""){
$order->isShippingDetail = 1;
}
if($request->has('order_notes')){
$order->notes = $request->order_notes;
}
$order->save();
$order_billing = new Order_Billing_Details;
$order_billing->order_id = $order->id;
$order_billing->first_name = $request->billing_first_name ;
$order_billing->last_name = $request->billing_last_name ;
$order_billing->company = $request->billing_company_name ;
$order_billing->address_line_1 = $line1;
$order_billing->address_line_2 = $line2;
$order_billing->state = $state;
$order_billing->city = $city;
$order_billing->postal_code = $zip;
$order_billing->email = $email;
$order_billing->phone = $phone;
$order_billing->save();
if($request->shipping_first_name <> ""){
$order_shipping = new Order_Shipping_Details;
$order_shipping->order_id = $order->id;
$order_shipping->first_name = $request->shipping_first_name ;
$order_shipping->last_name = $request->shipping_last_name ;
$order_shipping->company = $request->shipping_company_name ;
$order_shipping->address_line_1 = $request->shipping_address_1 ;
$order_shipping->address_line_2 = $request->shipping_address_2 ;
$order_shipping->state = $request->shipping_state ;
$order_shipping->city = $request->shipping_town ;
$order_shipping->postal_code = $request->shipping_zip ;
$order_shipping->email = $email ;
$order_shipping->phone = $request->shipping_phone ;
$order_shipping->save();
}
else{
$order_shipping = new Order_Shipping_Details;
$order_shipping->order_id = $order->id;
$order_shipping->first_name = $request->billing_first_name ;
$order_shipping->last_name = $request->billing_last_name ;
$order_shipping->company = $request->billing_company_name ;
$order_shipping->address_line_1 = $line1;
$order_shipping->address_line_2 = $line2;
$order_shipping->state = $state;
$order_shipping->city = $city;
$order_shipping->postal_code = $zip;
$order_shipping->email = $email;
$order_shipping->phone = $phone;
$order_shipping->save();
}
try {
// ### Create Payment
// Create a payment by posting to the APIService
// using a valid ApiContext
// The return object contains the status;
//dd(Paypalpayment::apiContext());
$payment->create(Paypalpayment::apiContext());
// dd($payment);
$arrpayment = $payment->toArray();
$order = Orders::find($saved_order_id);
$order->paypal_invoice = $arrpayment['id'];
$order->save();
} catch (\PPConnectionException $ex) {
echo $ex->getCode(); // Prints the Error Code
echo $ex->getData();
dd($ex);
return response()->json(["error" => $ex->getMessage()], 400);
}
catch (PayPal\Exception\PayPalConnectionException $ex) {
echo $ex->getCode(); // Prints the Error Code
echo $ex->getData(); // Prints the detailed error message
}
$email=$request->billing_email;
$fees=HandlingFee::find(1);
$fee = $fees->fee;
$data=array(
'order' => $order,
'name' => $request->billing_first_name.' '.$request->billing_last_name,
'email'=>$email,
'fee'=>$fee,
'payPalLink' => $payment->getApprovalLink(),
);
Mail::send('email.placed', $data, function($message) use ($email) {
$message->subject('New Order Received');
$message->from('no-reply#blurack.com', 'BluRack');
$message->to($email);
});
$admins=DB::table('users')
->select('updates_email')
->where('receiving_updates',1)
->where(function($q) {
$q->where('role','Administrator')
->orWhere('role','Retailer');
})->get()->toArray();
// ->where('role','Administrator')
// ->orWhere('role','Retailer')
// dd($admins);
foreach($admins as $admin){
$admin_mail=$admin->updates_email;
//dd($admin_mail);
Mail::send('email.orderplaced',$data, function($message) use ($admin_mail) {
$message->subject('New Order Received');
$message->from('no-reply#blurack.com', 'BluRack');
$message->to($admin_mail);
});
}
return redirect($payment->getApprovalLink());
// return response()->json([$payment->toArray(), 'approval_url' => $payment->getApprovalLink()],
200);
}
I think the issue is with try catch problem?
I have a loop for create or update data like below
foreach ($goods_list as $goods) {
$w_estim_mp = WEstimMp::where('event_seq', \LoginInfo::event_data()['event_seq'])
->where('goods_seq', $goods['goods_seq'])
->first();
if (!isset($goods['note'])) {
$goods['note'] = '';
}
if (!isset($w_estim_mp)) {
$w_estim_mp = new WEstimMp;
$w_estim_mp->event_seq = \LoginInfo::event_data();
$w_estim_mp->goods_seq = $goods['goods_seq'];
$w_estim_mp->mp_item_category = $mp_item_category;
}
$w_estim_mp->num = $goods['num'];
$w_estim_mp->note = $goods['note'];
$w_estim_mp->proc_flg = 2;
$now = (new \Carbon\Carbon())->format('Y-m-d H:i:s');
$w_estim_mp->update_dtime = $now;
$w_estim_mp->save();
}
I don't know why i can update only last value of $goods_list.
Help me T.T Thank you!
You can use array_pop to remove the last element and array_push to insert a new element. Follow an example:
<?php
$initial_array = [1,2,3];
function change_last($array, $value) {
$removed_element = array_pop($array);
array_push($array, $value);
return $array;
}
$changed_array = change_last($initial_array, 4);
print_r($changed_array);
?>
and here a live example:
https://tech.io/snippet-widget/ZfEzgjj
I resolved my question!
I don't know why but i work, finnaly, after i changed to
foreach ($goods_list as $goods) {
$goods_seq = $goods['goods_seq'];
$num = $goods['num'];
$w_estim = WEstimMp::where('event_seq', $event_seq)
->where('goods_seq', $goods_seq)
->first();
if (!isset($goods['note'])) {
$goods['note'] = '';
}
$now = (new \Carbon\Carbon())->format('Y-m-d H:i:s');
if (!isset($w_estim)) {
$w_estim = new WEstimMp;
$w_estim->event_seq = $event_seq;
$w_estim->goods_seq = $goods_seq;
$w_estim->mp_item_category = $mp_item_category;
$w_estim->num = $num;
$w_estim->note = $goods['note'];
$w_estim->proc_flg = 2;
$w_estim->update_dtime = $now;
$w_estim->save();
} else {
$w_estim = WEstimMp::where('event_seq', $event_seq)
->where('goods_seq', $goods_seq)
// ->first()
->update([
'num' => $num,
'note' => $goods['note'],
'proc_flg' => 2,
'update_dtime' => $now,
]);
}
i have a problem in my multiple filters implementation. I have some checkboxes that pass to AJAX some params that can have multiple values.
In my controller i have written this to handle this params:
function getCategoria(Request $request) {
$path_info = Request::getPathInfo();
$path = substr($path_info, 1);
$links = explode('/', $path);
$categorie = \App\Models\Categorie::where('primaria',1)->get();
$categoria = \App\Models\Categorie::where('link_statico', $path)->first();
$categoriaz = \App\Models\Categorie::where('link_statico', $path)->first();
$id = ucfirst($links[0]);
$prodottip = \App\Models\Prdotticategorie::where('prodotti2categorie.id_categoria', $categoriaz->id)->join('prodotti', 'prodotti.id', '=', 'prodotti2categorie.id_prodotto')->query();
$brands = Input::get('brands');
$genere = Input::get('genere');
$stagione = Input::get('stagione');
$this->data['links'] = $links;
$this->data['categorie'] = $categorie;
$this->data['categoria'] = $categoria;
$this->data['categoriaz'] = $categoriaz;
$this->data['id'] = $id;
$this->data['pages'] = 'categorie.frontend';
if(count($brands) > 0 && count($genere) > 0 && count($stagione) > 0)
{
if(count($brands) > 0)
{
$brands_array = [];
if(is_array($brands) || is_object($brands))
{
foreach ($brands as $brand)
{
$brands_array[] = $brand;
}
$rst = $prodottip->whereIn('prodotti.id_produttore', $brands_array);
}
}
if(count($genere) > 0)
{
$genere_array = [];
if(is_array($genere) || is_object($genere))
{
foreach ($genere as $gen)
{
$genere_array[] = $gen;
}
$rst = $prodottip->whereIn('prodotti.genere', $genere_array);
}
}
if (count($stagione) > 0)
{
$stagione_array = [];
if(is_array($stagione) || is_object($stagione))
{
foreach ($stagione as $stag)
{
$stagione_array[] = $gen;
}
$rst = $prodottip->whereIn('prodotti.stagione', $stagione_array);
}
}
$prodottix = $rst->paginate(18);
} else {
$prodottix = $prodottip->paginate(18);
}
$this->data['prodottix'] = $prodottix;
if (Request::ajax()) {
$page = 'layouts.'.CNF_THEME.'.categorie_ajax';
$view = view($page, $this->data)->render();
return response()->json(['html'=>$view]);
}
$page = 'layouts.'.CNF_THEME.'.categorie';
return view($page, $this->data);
}
The problem is that AJAX reload correctly but the results remaining the same. I can bring it working only if i an elseif with different scenarios like this:
if(count($brands) > 0 && count($genere) > 0 && count($stagione) > 0)
//query with 3 where
elseif(count($brands) > 0 && count($genere) == 0 && count($stagione) == 0)
// query with 1 where
Hi have read something on DynamicScopes in Laravel, but i need more help thks
function getCategoria(Request $request)
{
$path_info = Request::getPathInfo();
$path = substr($path_info, 1);
$links = explode('/', $path);
$categorie = \App\Models\Categorie::where('primaria', 1)->get();
$categoria = \App\Models\Categorie::where('link_statico', $path)->first();
$categoriaz = \App\Models\Categorie::where('link_statico', $path)->first();
$id = ucfirst($links[0]);
$prodottip = \App\Models\Prdotticategorie::where('prodotti2categorie.id_categoria', $categoriaz->id)->join('prodotti', 'prodotti.id', '=', 'prodotti2categorie.id_prodotto')->query();
$brands = Input::get('brands');
$genere = Input::get('genere');
$stagione = Input::get('stagione');
$this->data['links'] = $links;
$this->data['categorie'] = $categorie;
$this->data['categoria'] = $categoria;
$this->data['categoriaz'] = $categoriaz;
$this->data['id'] = $id;
$this->data['pages'] = 'categorie.frontend';
$rst = null;
if (count($brands) > 0) {
$brands = is_object($brands) ? array($brands) : $brands;
$rst = $prodottip->whereIn('prodotti.id_produttore', $brands);
}
if (count($brands) > 0) {
$genere = is_object($genere) ? array($genere) : $genere;
$rst = $prodottip->whereIn('prodotti.genere', $genere);
}
if (count($stagione) > 0) {
$stagione = is_object($stagione) ? array($stagione) : $stagione;
$rst = $prodottip->whereIn('prodotti.stagione', $stagione);
}
if(null !== $rst) {
$prodottix = $rst->paginate(18);
} else {
$prodottix = $prodottip->paginate(18);
}
$this->data['prodottix'] = $prodottix;
if (Request::ajax()) {
$page = 'layouts.' . CNF_THEME . '.categorie_ajax';
$view = view($page, $this->data)->render();
return response()->json(['html' => $view]);
}
$page = 'layouts.' . CNF_THEME . '.categorie';
return view($page, $this->data);
}
Considering $brands,$genere,$stagione are array by
default. If it is object then then type casting to array and using in
the query.
Removed first if condition which is checking count
of all 3 arrays and then trying to build up a query.
Created new variable $rst which is having default value as null. In any condition is satisfied then it will assign the query object to $rst.
At last checking is $rst not equal to null and calling its paginate method.
Hope this will clears to you and solve your problem. If not,at least you will get an idea how you can re-factor your code :)
function getCategoria(Request $request) {
$path_info = Request::getPathInfo();
$path = substr($path_info, 1);
$links = explode('/', $path);
$categorie = \App\Models\Categorie::where('primaria',1)->get();
$categoria = \App\Models\Categorie::where('link_statico', $path)->first();
$categoriaz = \App\Models\Categorie::where('link_statico', $path)->first();
$id = ucfirst($links[0]);
$prodottip = \App\Models\Prdotticategorie::where('prodotti2categorie.id_categoria', $categoriaz->id)->join('prodotti', 'prodotti.id', '=', 'prodotti2categorie.id_prodotto')->query();
$brands = Input::get('brands');
$genere = Input::get('genere');
$stagione = Input::get('stagione');
$this->data['links'] = $links;
$this->data['categorie'] = $categorie;
$this->data['categoria'] = $categoria;
$this->data['categoriaz'] = $categoriaz;
$this->data['id'] = $id;
$this->data['pages'] = 'categorie.frontend';
if(count($brands) > 0 && count($genere) > 0 && count($stagione) > 0)
{
if(count($brands) > 0)
{
$brands_array = [];
if(is_array($brands) || is_object($brands))
{
foreach ($brands as $brand)
{
$brands_array[] = $brand;
}
$prodottip = $prodottip->whereIn('prodotti.id_produttore', $brands_array);
}
}
if(count($genere) > 0)
{
$genere_array = [];
if(is_array($genere) || is_object($genere))
{
foreach ($genere as $gen)
{
$genere_array[] = $gen;
}
$prodottip = $prodottip->whereIn('prodotti.genere', $genere_array);
}
}
if (count($stagione) > 0)
{
$stagione_array = [];
if(is_array($stagione) || is_object($stagione))
{
foreach ($stagione as $stag)
{
$stagione_array[] = $gen;
}
$prodottip = $prodottip->whereIn('prodotti.stagione', $stagione_array);
}
}
}
$prodottix = $prodottip->paginate(18);
$this->data['prodottix'] = $prodottix;
if (Request::ajax()) {
$page = 'layouts.'.CNF_THEME.'.categorie_ajax';
$view = view($page, $this->data)->render();
return response()->json(['html'=>$view]);
}
$page = 'layouts.'.CNF_THEME.'.categorie';
return view($page, $this->data);
}
This file is the database ID information all the fields and went and came to a Blade, I want to an ID information entered in the same panel Blade I send my face.
class DataGrid extends DataSet
{
protected $fields = array();
/** #var Column[] */
public $columns = array();
public $headers = array();
public $rows = array();
public $output = "";
public $attributes = array("class" => "table");
public $checkbox_form = false;
protected $row_callable = array();
/**
* #param string $name
* #param string $label
* #param bool $orderby
*
* #return Column
*/
public function add($name, $label = null, $orderby = false)
{
$column = new Column($name, $label, $orderby);
$this->columns[$column->name] = $column;
if (!in_array($name,array("_edit"))) {
$this->headers[] = $label;
}
if ($orderby) {
$this->addOrderBy($column->orderby_field);
}
return $column;
}
//todo: like "field" for DataForm, should be nice to work with "cell" as instance and "row" as collection of cells
public function build($view = '')
{
($view == '') and $view = 'rapyd::datagrid';
parent::build();
Persistence::save();
foreach ($this->data as $tablerow) {
$row = new Row($tablerow);
foreach ($this->columns as $column) {
$cell = new Cell($column->name);
$sanitize = (count($column->filters) || $column->cell_callable) ? false : true;
$value = $this->getCellValue($column, $tablerow, $sanitize);
$cell->value($value);
$cell->parseFilters($column->filters);
if ($column->cell_callable) {
$callable = $column->cell_callable;
$cell->value($callable($cell->value, $tablerow));
}
$row->add($cell);
}
if (count($this->row_callable)) {
foreach ($this->row_callable as $callable) {
$callable($row);
}
}
$this->rows[] = $row;
}
$routeParamters = \Route::current()->parameters();
return \View::make($view, array('dg' => $this, 'buttons'=>$this->button_container, 'label'=>$this->label,
'current_entity' => $routeParamters['entity']));
}
public function buildCSV($file = '', $timestamp = '', $sanitize = true,$del = array())
{
$this->limit = null;
parent::build();
$segments = \Request::segments();
$filename = ($file != '') ? basename($file, '.csv') : end($segments);
$filename = preg_replace('/[^0-9a-z\._-]/i', '',$filename);
$filename .= ($timestamp != "") ? date($timestamp).".csv" : ".csv";
$save = (bool) strpos($file,"/");
//Delimiter
$delimiter = array();
$delimiter['delimiter'] = isset($del['delimiter']) ? $del['delimiter'] : ';';
$delimiter['enclosure'] = isset($del['enclosure']) ? $del['enclosure'] : '"';
$delimiter['line_ending'] = isset($del['line_ending']) ? $del['line_ending'] : "\n";
if ($save) {
$handle = fopen(public_path().'/'.dirname($file)."/".$filename, 'w');
} else {
$headers = array(
'Content-Type' => 'text/csv',
'Pragma'=>'no-cache',
'"Cache-Control' => 'must-revalidate, post-check=0, pre-check=0',
'Content-Disposition' => 'attachment; filename="' . $filename.'"');
$handle = fopen('php://output', 'w');
ob_start();
}
fputs($handle, $delimiter['enclosure'].implode($delimiter['enclosure'].$delimiter['delimiter'].$delimiter['enclosure'], $this->headers) .$delimiter['enclosure'].$delimiter['line_ending']);
foreach ($this->data as $tablerow) {
$row = new Row($tablerow);
foreach ($this->columns as $column) {
if (in_array($column->name,array("_edit")))
continue;
$cell = new Cell($column->name);
$value = str_replace('"', '""',str_replace(PHP_EOL, '', strip_tags($this->getCellValue($column, $tablerow, $sanitize))));
$cell->value($value);
$row->add($cell);
}
if (count($this->row_callable)) {
foreach ($this->row_callable as $callable) {
$callable($row);
}
}
fputs($handle, $delimiter['enclosure'] . implode($delimiter['enclosure'].$delimiter['delimiter'].$delimiter['enclosure'], $row->toArray()) . $delimiter['enclosure'].$delimiter['line_ending']);
}
fclose($handle);
if ($save) {
//redirect, boolean or filename?
} else {
$output = ob_get_clean();
return \Response::make(rtrim($output, "\n"), 200, $headers);
}
}
protected function getCellValue($column, $tablerow, $sanitize = true)
{
//blade
if (strpos($column->name, '{{') !== false ||
strpos($column->name, '{!!') !== false) {
if (is_object($tablerow) && method_exists($tablerow, "getAttributes")) {
$fields = $tablerow->getAttributes();
$relations = $tablerow->getRelations();
$array = array_merge($fields, $relations) ;
$array['row'] = $tablerow;
} else {
$array = (array) $tablerow;
}
$value = $this->parser->compileString($column->name, $array);
//eager loading smart syntax relation.field
} elseif (preg_match('#^[a-z0-9_-]+(?:\.[a-z0-9_-]+)+$#i',$column->name, $matches) && is_object($tablerow) ) {
//switch to blade and god bless eloquent
$_relation = '$'.trim(str_replace('.','->', $column->name));
$expression = '{{ isset('. $_relation .') ? ' . $_relation . ' : "" }}';
$fields = $tablerow->getAttributes();
$relations = $tablerow->getRelations();
$array = array_merge($fields, $relations) ;
$value = $this->parser->compileString($expression, $array);
//fieldname in a collection
} elseif (is_object($tablerow)) {
$value = #$tablerow->{$column->name};
if ($sanitize) {
$value = $this->sanitize($value);
}
//fieldname in an array
} elseif (is_array($tablerow) && isset($tablerow[$column->name])) {
$value = $tablerow[$column->name];
//none found, cell will have the column name
} else {
$value = $column->name;
}
//decorators, should be moved in another method
if ($column->link) {
if (is_object($tablerow) && method_exists($tablerow, "getAttributes")) {
$array = $tablerow->getAttributes();
$array['row'] = $tablerow;
} else {
$array = (array) $tablerow;
}
$value = ''.$value.'';
}
if (count($column->actions)>0) {
$key = ($column->key != '') ? $column->key : $this->key;
$keyvalue = #$tablerow->{$key};
$routeParamters = \Route::current()->parameters();
$value = \View::make('rapyd::datagrid.actions', array('uri' => $column->uri, 'id' => $keyvalue, 'actions' => $column->actions,
'current_entity' => $routeParamters['entity']));
}
return $value;
}
public function getGrid($view = '')
{
$this->output = $this->build($view)->render();
return $this->output;
}
public function __toString()
{
if ($this->output == "") {
//to avoid the error "toString() must not throw an exception"
//http://stackoverflow.com/questions/2429642/why-its-impossible-to-throw-exception-from-tostring/27307132#27307132
try {
$this->getGrid();
}
catch (\Exception $e) {
$previousHandler = set_exception_handler(function (){ });
restore_error_handler();
call_user_func($previousHandler, $e);
die;
}
}
return $this->output;
}
public function edit($uri, $label='Edit', $actions='show|modify|delete', $key = '')
{
return $this->add('_edit', $label)->actions($uri, explode('|', $actions))->key($key);
}
public function getColumn($column_name)
{
if (isset($this->columns[$column_name])) {
return $this->columns[$column_name];
}
}
public function addActions($uri, $label='Edit', $actions='show|modify|delete', $key = '')
{
return $this->edit($uri, $label, $actions, $key);
}
public function row(\Closure $callable)
{
$this->row_callable[] = $callable;
return $this;
}
protected function sanitize($string)
{
$result = nl2br(htmlspecialchars($string));
return Config::get('rapyd.sanitize.num_characters') > 0 ? str_limit($result, Config::get('rapyd.sanitize.num_characters')) : $result;
}
public function rowCount()
{
return count($this->rows);
}
}
This is the source of a rapyd-laravel widget/package, not a custom code.
According to DataGrid/DataSet documentation, you can use many sources:
https://github.com/zofe/rapyd-laravel/wiki/DataSet
DataSet/DataGrid are presenters, you can retrieve all data of your data source using
{{ $item->field }} or {{ $row->field }} respectively
See the docs please
https://github.com/zofe/rapyd-laravel/wiki