I want to implement infinite scroll in sub comments, but I have no idea what to do. I've tried to push the addition data, but nothing is gonna work.
public function mount($link)
{
$this->link = $link;
$campaign = Campaign::where('status', 1)->where('link', $this->link)->first();
if ($campaign) {
$this->campaignId = $campaign->id;
$this->campaign = $campaign;
$this->comments = new Collection();
$this->subComments = new Collection();
$this->loadFirst();
}
}
public function loadSubData($parentCommentId)
{
$this->perPage++;
$this->comments1 = Comment::orderBy('id', 'desc')->where('campaign_id', $this->campaignId)->cursorPaginate(3, ['*'], 'cursor', Cursor::fromEncoded($this->nextCursor));
$this->comments1->getCollection()->transform(function ($value) use ($parentCommentId) {
$datas = [];
$userComment = User::where('id', $value->user_id)->first();
$countSubComments = SubComment::orderBy('id', 'desc')->where('parent_comment_id', $value->id)->get();
$datas['id'] = $value->id;
$datas['user_id'] = $userComment;
$datas['comment'] = $value->comment;
$datas['updated_at'] = $value->updated_at;
$datas['count_sub_comment'] = count($countSubComments);
$this->subComments1 = SubComment::orderBy('id', 'desc')->where('parent_comment_id', $parentCommentId)->cursorPaginate($this->perPage, ['*'], 'cursor', Cursor::fromEncoded($this->nextCursorSubComment));
$datas['sub_comments'] = $this->subComments1->getCollection()->transform(function ($subValue) {
$datas2 = [];
$userSubComment = User::where('id', $subValue->user_id)->first();
$datas2['id'] = $subValue->id;
$datas2['user'] = $userSubComment;
$datas2['sub_comment'] = $subValue->sub_comment;
$datas2['updated_at'] = $subValue->updated_at;
$datas2['has_more_pages'] = $this->subComments1->hasMorePages();
return $datas2;
});
$this->subComments->push(...$datas['sub_comments']); // problem here
return $datas;
});
}
Actually, is more easier to do infinite scroll in parent comments, just add piece of code below:
public function loadMoreComments()
{
if ($this->hasMorePages !== null && !$this->hasMorePages) {
return;
}
$this->loadAllData();
$this->comments->push(...$this->comments1->items()); // $this->comments1 is new coming data
if ($this->hasMorePages = $this->comments1->hasMorePages()) {
$this->nextCursor = $this->comments1->nextCursor()->encode();
}
}
But it's more tricky when I've tried this in sub comments.
So, the expectation when users click view more comments, loadSubData($id) is called.
Related
I was trying to add new items to a session container, and if old items are available then I'll just push the new items to the container. Now whenever I'm adding new items it's storing the current item by replacing the previous item, where is the issue?
In Controller my function to add new items
public function addToCart($id)
{
$product = Product::findOrFail($id);
$oldCart = Session::has("cart") ? Session::get("cart") : null;
$cart = new Cart($oldCart);
$cart->addNewItem($id, $product);
Session::put("cart", $cart);
dd(Session::get("cart"));
}
In Class
class Cart
{
public $items = null;
public $totalQty = 0;
public $totalPrice = 0;
public function __construct($oldCart)
{
if ($oldCart) {
$this->items = $oldCart->items;
$this->totalQty = $oldCart->totalQty;
$this->totalPrice = $oldCart->totalPrice;
}
}
public function addNewItem($id, $item)
{
$storeNewItem["product_id"] = $item->id;
$storeNewItem["product_name"] = $item->product_name;
$storeNewItem["product_price"] = $item->product_price;
$this->totalQty++;
$this->totalPrice += $item->product_price;
$this->items[$id] = $storeNewItem;
}
}
In Cart Class
public function addNewItem($id,$item) {
$storeNewItem["product_id"] = $item->id;
$storeNewItem["product_name"] = $item->product_name;
$storeNewItem["product_price"] = $item->product_price;
$this->totalQty++;
$this->totalPrice += $item->product_price;
return [
'totalQty', => $this->totalQty,
'totalPrice', => $this->totalPrice,
'items[$id]', => $storeNewItem,
]
}
In Controller addToCart Function
$newCart = $cart->addNewItem($id,$product);
Session::put("cart",$newCart );
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.
i am trying to create a CRUD app and am having trouble, if anyone can point me in the right direction i would be grateful, thank you.
Hi there i am having difficulty using data from the json.
i have used it here and it as worked
class JsonUtility
{
public static function makeProductArray(string $file) {
$string = file_get_contents($file);
$productsJson = json_decode($string, true);
$products = [];
foreach ($productsJson as $product) {
switch($product['type']) {
case "cd":
$cdproduct = new CdProduct($product['id'],$product['title'], $product['firstname'],
$product['mainname'],$product['price'], $product['playlength']);
$products[] = $cdproduct;
break;
case "book":
$bookproduct = new BookProduct($product['id'],$product['title'], $product['firstname'],
$product['mainname'],$product['price'], $product['numpages']);
$products[]=$bookproduct;
break;
}
}
return $products;
}
this is my controller
public function index()
{
// create a list.
$products = JsonUtility::makeProductArray('products.json');
return view('products', ['products'=>$products]);
}
this is my route
Route::get('/product' , [ProductController::class, 'index'] );
how can i use this on my controller and what route should i set up to create a product
public static function addNewProduct(string $file, string $producttype, string $title, string $fname, string $sname, float $price, int $pages)
{
$string = file_get_contents($file);
$productsJson = json_decode($string, true);
$ids = [];
foreach ($productsJson as $product) {
$ids[] = $product['id'];
}
rsort($ids);
$newId = $ids[0] + 1;
$products = [];
foreach ($productsJson as $product) {
$products[] = $product;
}
$newProduct = [];
$newProduct['id'] = $newId;
$newProduct['type'] = $producttype;
$newProduct['title'] = $title;
$newProduct['firstname'] = $fname;
$newProduct['mainname'] = $sname;
$newProduct['price'] = $price;
if($producttype=='cd') $newProduct['playlength'] = $pages;
if($producttype=='book') $newProduct['numpages'] = $pages;
$products[] = $newProduct;
$json = json_encode($products);
if(file_put_contents($file, $json))
return true;
else
return false;
}
This is where i am trying to type to code into.
public function create()
{
//show a view to create a new resource
$products = JsonUtility::addNewProduct('products.json');
return view('products', ['products'=>$newProduct], );
}
your function addNewProduct() is expecting 7 parameters when called.
you are getting this error because you cannot provide those parameters that your function is looking for.
in your code above you are passing 'products.json' which is in a string format.
lets assume that it is a JSON data. it will still fail because you are only passing 1 parameter to a function that is expecting 7 parameters.
what you could probably do is change it to
public static function addNewProduct($data)
{
// code here
}
then you can pass your JSON data and then go through each of your json using a loop.
I want to add the Interest_status key on my response. But shows me error. Here is my code. Please Help. Thanks in advance.
$activities_status = [];
$activities = [];
foreach ($activitiesDetail as $activityDetail) {
$activity = '';
if(in_array($activityDetail->user_id, $userFriendIds))
{
$activity = Activity::where('id', $activityDetail->id)->with('joins')->get();
}
else {
$activity = Activity::where('id', $activityDetail->id)
->where('activity_privacy_visible', 0)->with('joins')->get();
}
$interest = $authUser->interests()->where('activity_id', $activity->id)->first();
if($interest)
{
$status['interest_status'] = $interest->status;
$activities_status[] = array_merge($status, $activity->toArray());
} else {
$status['interest_status'] = NULL;
$activities_status[] = array_merge($status, $activity->toArray());
}
$activities = array_merge($activities, $activities_status);
}
return response()->json(['filter'=> $activities], 200);
If I print the Interest_status it gives me the value of status but I return the whole response it shows error.Please Help.
I need to rename the file on file upload and inserting to the database.
I search for ways but i can't find the right code.
I tried to use callback but it did not work.
Here's my code:
public function home()
{
$crud = new grocery_CRUD();
$crud->set_theme('datatables');
$crud->set_table('blog_post');
$crud->set_field_upload('post_image',UPLOAD_PATH);
$crud->callback_before_upload(array($this,'_before_upload'))
$crud->callback_before_insert(array($this,'rename_img_db'));
$output = $crud->render();
$this->_example_output($output);
}
function rename_img_db($post_array)
{
if (!empty($post_array['post_image'])) {
$ext = end(explode(".",$post_array['post_image']));
$img_name = $post_array['post_image'] = mktime().".".$ext;
$post_array['post_image'] = $img_name;
}
return $post_array;
}
function _before_upload($files_to_upload,$field_info)
{
foreach($files_to_upload as $value) {
$ext = pathinfo($value['name'], PATHINFO_EXTENSION);
$rename = $value['name'];
}
$allowed_formats = array("jpg","gif","png","doc","docx","pdf");
if(in_array($ext,$allowed_formats))
{
return true;
}
else
{
return 'Wrong file format';
}
if ($rename) {
$ext1 = end(explode(".",$rename));
$img_name = $rename = mktime().".".$ext1;
$rename = $img_name;
return $rename;
}
}
I noticed a tipo in your line: $crud->callback_before_upload(array($this,'_before_upload'))
Moreover I had to do something similar and I used the callback_after_insert, then you can get the $primary_key variable and with that update the element, something like this:
$crud->callback_after_insert(array($this, 'rename_img_db'));
public function rename_img_db($post_array,$primary_key)
{
//Here goes the get and set querys with your $primary_key
}