How to use Laravel Collection groupBy along with Pagination? - laravel

Hi I am trying to do this query
public function execute() {
return $this->applyModelFilter(Document::with('contact', 'sales_person','document_detail','contact_profile')->invoices())->chunkMap(function ($invoice) {
return $this->mapColumns($invoice);
}, $this->chunkSize)->groupBy($this->groupByFormatted)
->map(function ($group) {
return [
'summary' => $this->getSummary($group),
'transactions' => $this->paginateCollection($group->all()),
'group_name' => $group->first()->get($this->groupByFormatted),
'group_count' => $group->count(),
];
})->values();
}
////
public function paginateCollection($items, $perPage = 5, $page = null, $options = [])
{
$page = $page ?: (\Illuminate\Pagination\Paginator::resolveCurrentPage() ?: 1);
$items = $items instanceof \Illuminate\Support\Collection ? $items : \Illuminate\Support\Collection::make($items);
return new \Illuminate\Pagination\LengthAwarePaginator(array_values($items->forPage($page, $perPage)->toArray()), $items->count(), $perPage, $page, $options);
}
But it displays pagination only in transaction, i want pagination for whole data.
So I wonder how can I do that without to lose the paginate function ? Thanks.

Related

Need to get data with laravel when query

I am trying to filter data using when query in Laravel, where it should filter data using the filter $sortBy or $categoryId. Please note the all 3 fields like $id $sortBy $categoryId are optional and will not be presented in all queries
public function Products(Request $request)
{
$page = $request->has('page') ? $request->get('page') : 1;
$limit = $request->has('itemsPerPage') ? $request->get('itemsPerPage') : 10;
$sortBy = (($request->sortBy == "popularity") ? "viewCount" : "created_at");
$categoryId= $request->get('categoryId');
$sellerId = $request->header('id')?SellersBranding::findOrFail($request->header('id')):"Null";
$productLive = ProductsLive::select('productTitle', 'product_id', 'brand_id', 'category_id')
->when($sellerId=="Null", function($query) use ($page, $limit){
return $query->where('status', 'active')
->limit($limit)->offset(($page - 1) * $limit);
})
->when($sortBy, function ($query) use ($sortBy, $sellerId, $page, $limit){
return $query->orderBy($sortBy, 'DESC')
->where('Sid', $sellerId->id)
->where('status','active')
->limit($limit)->offset(($page - 1) * $limit);
})
->when($categoryId, function ($query) use ($categoryId, $sellerId, $page, $limit) {
->where('Sid', $sellerId->id)
->where(['category_id' => $categoryId, 'status' => 'active'])
->limit($limit)->offset(($page - 1) * $limit)
->inRandomOrder();
})->get();
}
i am new in php and also in laravel please help how to get filtered data
i cleanup your code you can check this
public function Products(Request $request)
{
$page = $request->has('page') ? $request->get('page') : 1;
$limit = $request->has('itemsPerPage') ? $request->get('itemsPerPage') : 10;
$sortBy = (($request->sortBy == "popularity") ? "viewCount" : "created_at");
$categoryId= $request->filled('categoryId');
$seller = $request->header('id') ? SellersBranding::findOrFail($request->header('id')): null;
$productLive = ProductsLive::select('productTitle', 'product_id', 'brand_id', 'category_id')
->when($seller ,function ($query) use ($seller){
$query->where('Sid', $seller->id);
})
->when($categoryId ,function ($query)){
$query->where('category_id', request('categoryId'))
->inRandomOrder();
})
->where('status','active')
->orderBy($sortBy, 'DESC')
->limit($limit)->offset(($page - 1) * $limit);
return $productLive;
}
here when() something filter is coming we are only applying condition.
Not returning each filter as you did

get page number in object of laravel

i have object given below and i wanted to pagination in this how can i get
$productListArray = array();
$productListObject = ((object)[
"id"=>$productList->id,
"title"=>$productList->title,
"slug"=>$productList->slug,
'categoryName'=>$categoryName[0]->cat_title,
'brand'=>$brandName[0]->brandname,
'minMrp'=>$minMrp,
'maxMrp' =>$maxMrp,
'minSellingPrice' => $minSellingPrice,
'maxSellingPrice' => $maxSellingPrice,
'rating'=>$productList->rating,
'rating_count' => $productList->rating_count,
'image' => $img[0]
])->paginate();
array_push($productListArray, $productListObject);
}
return response()->json($productListArray, 200);
Hi you can get the Current page using laravel paginator Paginator::currentPageResolver
public function index()
{
$currentPage = 3; // You can set this to any page you want to paginate to
// Make sure that you call the static method currentPageResolver()
// before querying users
Paginator::currentPageResolver(function () use ($currentPage) {
return $currentPage;
});
$users = \App\User::paginate(5);
return view('user.index', compact('users'));
}
thanks for your support i found solution,
first add on your header
use Illuminate\Pagination\Paginator;
use Illuminate\Support\Collection;
use Illuminate\Pagination\LengthAwarePaginator;
then make an other function
public function paginate($items, $perPage = 5, $page = null, $options = [])
{
$page = $page ?: (Paginator::resolveCurrentPage() ?: 1);
$items = $items instanceof Collection ? $items : Collection::make($items);
return new LengthAwarePaginator($items->forPage($page, $perPage), $items->count(), $perPage, $page, $options);
}
after than call this function where you want in class
$data = $this->paginate($productListArray);
return response()->json($data, 200);
last 2 lines already mentioned in my questions
thanks again

Paginate for a collection, Laravel

I try to add some new values to each user from foreach, but because I use get, now I can't use paginate on response, but I also need to add that values to each user. Any ideas?
public function statistics()
{
$users = User::select(['id', 'name'])->get();
foreach ($users as $key => $user) {
$history = AnswerHistory::where('user_id', '=', $user->id)->get();
$user->total_votes = count($history);
$user->total_time = gmdate("H:i:s", ($history->sum('answer_time')));
}
return response()->json($users);
}
what you want is not possible in laravel by default, however there are a few things you can do.
Solution one you can return paginator first and then modify the collection.
$users = User::select(['id', 'name'])->paginate(4)->toArray();
$users['data'] = array_map(function ($user) {
$history = AnswerHistory::where('user_id', '=', $user->id)->get();
$user->total_votes = count($history);
$user->total_time = gmdate("H:i:s", ($history->sum('answer_time')));
return $user;
}, $users['data']);
return $users;
Solution two The macro way. If you prefer, add the Collection macro to a Service Provider. That way you can call paginate() on any collection:
See AppServiceProvider.php for a sample implementation.
public function boot()
{
Collection::macro('paginate', function ($perPage, $total = null, $page = null, $pageName = 'page') {
$page = $page ?: LengthAwarePaginator::resolveCurrentPage($pageName);
return new LengthAwarePaginator(
$this->forPage($page, $perPage),
$total ?: $this->count(),
$perPage,
$page,
[
'path' => LengthAwarePaginator::resolveCurrentPath(),
'pageName' => $pageName,
]
);
});
}
and then your code will be like this
$users = User::select(['id', 'name'])->get();
foreach ($users as $key => $user) {
$history = AnswerHistory::where('user_id', '=', $user->id)->get();
$user->total_votes = count($history);
$user->total_time = gmdate("H:i:s", ($history->sum('answer_time')));
}
return response()->json($users->paginate(4));
Solution three The subclass way. Where you want a "pageable" collection that is distinct from the standard Illuminate\Support\Collection, implement a copy of Collection.php in your application and simply replace your use Illuminate\Support\Collection statements at the top of your dependent files with use App\Support\Collection:
<?php
namespace App\Support;
use Illuminate\Pagination\LengthAwarePaginator;
use Illuminate\Support\Collection as BaseCollection;
class Collection extends BaseCollection
{
public function paginate($perPage, $total = null, $page = null, $pageName = 'page')
{
$page = $page ?: LengthAwarePaginator::resolveCurrentPage($pageName);
return new LengthAwarePaginator(
$this->forPage($page, $perPage),
$total ?: $this->count(),
$perPage,
$page,
[
'path' => LengthAwarePaginator::resolveCurrentPath(),
'pageName' => $pageName,
]
);
}
}
and your code will be like this
// use Illuminate\Support\Collection
use App\Support\Collection;
$users = User::select(['id', 'name'])->get();
foreach ($users as $key => $user) {
$history = AnswerHistory::where('user_id', '=', $user->id)->get();
$user->total_votes = count($history);
$user->total_time = gmdate("H:i:s", ($history->sum('answer_time')));
}
return response()->json((new Collection($users))->paginate(4);
According to your post, User has many AnswerHistory. You can build relationship between them.
So getting the total_votes and total_time by withCount:
$users = User::withCount('answerHistories AS total_votes')
->withCount(['answerHistories AS total_time' => function($query) {
$query->select(DB::raw("SUM(answer_time)"));
}])->paginate(10);
And you can get the pagination datas by getCollection, and change the datas inside:
$users->getCollection()->transform(function ($data) {
$data->total_time = gmdate('H:i:s', $data->total_time);
return $data;
});
You can create pagination by yourself look to this Laravel doc https://laravel.com/docs/7.x/pagination#manually-creating-a-paginator.
I will suggest to use LengthAwarePaginator
Here is some code example with array
// creating pagination
$offset = max(0, ($page - 1) * $perPage);
$resultArray = array_slice($result, $offset, $perPage);
$paginator = new LengthAwarePaginator($resultArray, count($result), $perPage, $page);
$paginator->setPath(url()->current());
$paginator->appends(['per_page' => $perPage]);
return response()->json([
'message' => 'Success',
'data' => $paginator
]);
But I think your case have better "good" solution, you can load AnswerHistory with hasMany Laravel relation and with function.

How to update 2 table data using query builder

I have problem with edit and update with 2 table using query builder.
--->After i press button submit--->the data insert new row---> not update current data.
This is my function edit(only for view old data)
public function edit(Request $request, $id){
$tax_rate = TaxRate::find($id);
$tax_rate_details = TaxRateDetail::where('tax_rate_id', $id)->get();
$country = Country::all();
$geo_zones = GeoZone::all();
//dd($tax_rate);
//dd($tax_rate_details);
//dd($geo_zones);
if(!$tax_rate) {
return redirect('/');
}
return view('tax_management.edit',['country' => $country , 'tax_rate'=>$tax_rate , 'geo_zones'=>$geo_zones, 'tax_rate_details'=>$tax_rate_details]);
}
This is my update(i do validation and the saveTax is the saving part)
public function update(Request $request, $id){
$this->validate($request,[
'country_id'=> 'required',
'tax_type' => 'required',
'name' => 'required|max:100',
'code' => 'required|max:50'
]);
//dd($request->input());
DB::beginTransaction();
try{
$tax_rate = TaxRate::find($id);
$tax_rate_details = TaxRateDetail::where('tax_rate_id', $id)->get();
$this->saveTax($request, $tax_rate);
DB::commit();
return redirect()->route('tax_management.index');
} catch (\Exception $ex){
//dd($ex);
DB::rollback();
return back()->withInput()->withErrors('Fail to save');
}
}
This is my function save()
private function saveTax(Request $request, $tax_rate){
$tax_rate->country_id = $request->input('country_id');
$tax_rate->geo_zone_id = $request->input('geo_zone_id');
$tax_rate->tax_type = $request->input('tax_type');
$tax_rate->name = $request->input('name');
$tax_rate->code = $request->input('code');
$tax_rate->description = $request->input('description');
if(!empty($request->input('active'))){
$tax_rate->active =1;
} else {
$tax_rate->active =0;
}
$tax_rate->save();
if($tax_rate->tax_rate_id) {
TaxRateDetail::where('tax_rate_id', $tax_rate->tax_rate_id)->delete();
}
if($request->input('tax_rate_details')){
foreach ($request->input('tax_rate_details') as $key => $value) {
$tax_rate_detail = new TaxRateDetail();
$tax_rate_detail->tax_rate_id = $tax_rate->tax_rate_id;
$tax_rate_detail->priority = $value['priority'];
$tax_rate_detail->date_from = $value['date_from'];
$tax_rate_detail->date_to = $value['date_to'];
$tax_rate_detail->rate = $value['rate'];
$tax_rate_detail->type = $value['type'];
$tax_rate_detail->active = $value['active'];
//dd($tax_rate_detail);
$tax_rate_detail->save();
}
}
}
I want to save edit update with old(id). not create new. Please help thank you. I don't know where the code gone wrong.

Two lots of pagination with codeigniter on one page

I have to lots of paginations one lot is for my user's results and the other is for my question results.
When I am on link 3 on my question results it also switches the results on users list pagination.
Question if I click on the questions pagination links how can I make sure it does not affect the results of the user's list.
I have tried this Best way to do multiple pagination on one page in codeigniter does not work
As you can see in image below because I am on questions list page 3 it has effected the users list
<?php
class Dashboard extends MY_Controller {
public $data = array();
public function __construct() {
parent::__construct();
$this->load->model('user/user_model');
$this->load->model('forum/question_model');
$this->load->library('pagination');
}
public function index() {
$this->data['title'] = 'Dashboard';
$this->data['is_logged'] = $this->session->userdata('is_logged');
$config1['base_url'] = base_url('dashboard/');
$config1['total_rows'] = $this->user_model->total_users();
$config1['per_page'] = 2;
$config1['uri_segment'] = 2;
$config1['num_links'] = 200;
$config1['use_page_numbers'] = FALSE;
$config1['prefix'] = 'u_';
$pagination1 = new CI_Pagination();
$pagination1->initialize($config1);
$this->data['pagination1'] = $pagination1->create_links();
$page_segment1 = explode('_', $this->uri->segment(2));
$page1 = ($this->uri->segment(2)) ? $page_segment1[1] : 0;
$this->data['users'] = array();
$users = $this->user_model->get_users($config1['per_page'], $page1);
foreach ($users as $user) {
$this->data['users'][] = array(
'user_id' => $user['user_id'],
'username' => $user['username'],
'status' => ($user['status']) ? 'Enabled' : 'Disabled',
'warning' => '0' . '%',
'date' => date('d-m-Y H:i:s A', $user['date_created_on']),
'href' => site_url('user/profile/') . $user['user_id']
);
}
// Questions Pagination & Results
$config2['base_url'] = base_url('dashboard/');
$config2['total_rows'] = $this->question_model->total_questions();
$config2['per_page'] = 2;
$config2['uri_segment'] = 2;
$config2['num_links'] = 200;
$config2['use_page_numbers'] = FALSE;
$config2['prefix'] = 'q_';
$pagination2 = new CI_Pagination();
$pagination2->initialize($config2);
$this->data['pagination2'] = $pagination2->create_links();
$page_segment2 = explode('_', $this->uri->segment(2));
$page2 = ($this->uri->segment(2)) ? $page_segment2[1] : 0;
$this->data['questions'] = array();
$questions = $this->question_model->get_questions($config2['per_page'], $page2);
foreach ($questions as $question) {
$this->data['questions'][] = array(
'user_id' => $question['user_id'],
'title' => $question['title']
);
}
$this->data['navbar'] = $this->load->view('common/navbar', $this->data, TRUE);
$this->data['header'] = $this->load->view('common/header', $this->data, TRUE);
$this->data['footer'] = $this->load->view('common/footer', '', TRUE);
$this->load->view('common/dashboard', $this->data);
}
}
Question Model
<?php
class Question_model extends CI_Model {
public function get_questions($limit, $start) {
$this->db->select('*');
$this->db->from('questions q');
$this->db->join('users u', 'u.user_id = q.user_id', 'left');
$this->db->limit($limit, $start);
$query = $this->db->get();
return $query->result_array();
}
public function total_questions() {
return $this->db->count_all("questions");
}
}
Users Model
<?php
class User_model extends CI_Model {
public function get_users($limit, $start) {
$this->db->select('u.status, u.date_created_on, ud.*');
$this->db->from('users u', 'left');
$this->db->join('users_userdata ud', 'ud.user_id = u.user_id', 'left');
$this->db->limit($limit, $start);
$query = $this->db->get();
return $query->result_array();
}
public function total_users() {
return $this->db->count_all("users");
}
}

Resources