I am trying to use offset and limit on Laravel eloquent.
$start_from = 0;
$limit = 2;
$invoices = Invoice::where('calculation_complete',0)
->offset($start_from)
->limit($limit)
->get();
Instead of giving me 2 record it is giving me all the records. Where it is going wrong I am using it on other places there it is working fine.
Laravel has own function skip for offset and take for limit.
Try this:
$start_from = 0;
$limit = 2;
$invoices = Invoice::where('calculation_complete',0)
->orderBy('id','DESC')
->skip($start_from)
->take($limit)
->get();
Or, you can use paginate:
$invoices = Invoice::where('calculation_complete',0)
->orderBy('updated_at', 'desc')->paginate($limit);
Related
Laravel version 4.2
I'm having issues with this one problem I have.
I need to fill a quota of 5 results however I only have an array size of 3. I also need the rows to be selected randomly from the Array.
*edit: Fetching all results is not feasible
$store_id_array = array('111', '222' , '333');
$reviews = Review::whereIn('store_id', $store_id_array)
->take(5)
->get();
return Response::json($reviews);
This will return 5 results however only from the first item in the array.
How do I select randomly from the array items?
For Laravel below version 5:
orderBy(DB::raw('RAND()')) like this:
$reviews = Review::whereIn('store_id', $store_id_array)
->orderBy(DB::raw('RAND()'))
->take(5)
->get();
For Laravel 5.0 +
use inRandomOrder() method:
$reviews = Review::whereIn('store_id', $store_id_array)
->inRandomOrder()
->take(5)
->get();
public function index()
{
$categories = Category::latest()->get();
$protfolios = Protfolio::all();
$randompost = Post::approved()->publish()->take(4)->InRandomOrder()->get();
$allposts = Post::where('price', 0)->approved()->publish()->take(8)->get();
$posts = Post::latest()->where('price', '>=', 0)->approved()->publish()->take(8)->get();
$latestposts = Post::latest()->approved()->publish()->take(8)->get();
return view('welcome',compact('posts','randompost ','categories','allposts','latestposts','protfolios'));
}
$rowsPerPage = 50;
$num = 1;
$offsets = ($num - 1) * $rowsPerPage;
$data['trans'] = Transaction::withoutBranch()
->select('id', 'amount')
->where('payment_date', '>=', '2019-06-07')
->limit($offsets)
->get();
I'm using Laravel 4.2 to do the planning. I trying to get the data from data with 50 on the first page then the second page will get another new 50 data.
I did try the code but it still gets all of the data from the database.
Please try following:
$data['trans'] = Transaction::withoutBranch()
->select('id', 'amount')
->where('payment_date', '>=', '2019-06-07')
->limit($rowsPerPage)
->offset($offsets)
->get();
i have a simple where query that repeats in a foreach for some times that can be a lot really so here is my query :
for ($i = 0; $i < count($hasdate); $i++) {
$roomprice = RoomPricingHistory::
Where('accommodation_room_id', $hasroom[$i])
->where('from_date', '<=', $hasdate[$i])
->where('to_date', '>=', $hasdate[$i])
->get()->sortBy('created_at');
$lastget = last($roomprice);
$last_price = last($lastget);
if ($last_price) {
$final_price[] = $last_price->sales_price;
} else {
$has_not_capacity = $hasdate[$i];
}
}
so each time this runs it takes a bout 2,509.10ms in telescope and here is what the telescope shows me as the query which is running on table
select
*
from
`room_pricing_histories`
where
`accommodation_room_id` = 3
and `from_date` <= "2019-06-01 09:00:00"
and `to_date` >= "2019-06-01 09:00:00"
so any idea on how to optimize this query ??
Well, as a rule of thumb - don't run a query inside a loop.
You can use whereIn() for the querying multiple IDs
$roomIds = $hasroom // assume this has array of ids
$roomprice = RoomPricingHistory::
whereIn('accommodation_room_id', $roomIds)
->where('from_date', '<=', $fromDate)
->where('to_date', '>=', $toDate)
->get()->sortBy('created_at');
I am trying to union 3 SQL query, so I can orderBy the duedates as newDate and make a manually create paginator.
But for some reason is throwing this exception:
array_slice() expects parameter 1 to be array, object given
my code:
public function index(Request $request)
{
$TMUDue = Equipments::Where('due1', '<>', '1990-01-01')
->select('*', 'due1 AS newDate');
$CalDue = Equipments::Where('due2', '<>', '1990-01-01')
->select('*', 'due2 AS newDate');
$SerDue = Equipments::Where('due3', '<>', '1990-01-01')
->select('*', 'due3 AS newDate');
$equipmentsDue = $SerDue->union($CalDue)->union($TMUDue)->orderBy('newDate')->get();
$page = Input::get('page', 1);
$paginate = 10;
$offSet = ($page * $paginate) - $paginate;
$itemsForCurrentPage = array_slice($equipmentsDue, $offSet, $paginate, true);
$equipmentsDue = new \Illuminate\Pagination\LengthAwarePaginator($itemsForCurrentPage, count($equipmentsDue), $paginate, $page);
return view('dashboard.index', compact('equipmentsDue'));
Am i doing something wrong?
Without manually creation of the database pagination the query works fine.
It clearly says that you need to pass array instead collection , so change it with ->toArray();
$equipmentsDue = $SerDue->union($CalDue)
->union($TMUDue)->orderBy($sort , $sort2)->get()->toArray();
I am new to Laravel 4.2.
I need to do some pagination in my view search result page.
What I am doing is writing this code in the controller -
public function getSpecials()
{
$title = "Specials";
$info = DB::table(DB::raw('`car` , `available_car`, `users`'))
->select('car.car_maker', 'car.car_model', 'available_car.car_price', 'car.car_production_year', 'available_car.car_id', 'available_car.id', 'available_car.current_position')
->where('available_car.car_id', '`car`.`car_id`')
->where('available_car.is_sold', 'no')
->whereRaw('`available_car`.`created_at` BETWEEN NOW() - INTERVAL 30 DAY AND NOW()')
->orderByRaw('WEEK(`available_car`.`created_at`) DESC')
->orderBy('available_car.car_price', 'desc')
->orderBy('users.last_paid_date', 'desc')
->orderBy('available_car.created_at', 'desc')
->distinct()
->get();
$pagination = Paginator::make($info, count($info), 5);
//var_dump($pagination );
return View::make('specials',compact('pagination'))->with('info',$info)->with('title',$title);
}
I want to show 5 items per page. So I am doing paginate like this -
$pagination = Paginator::make($info, count($info), 5);
But the problem here is I am getting paginate number in the page perfectly.
But, All page is showing the whole result, not showing only 5 items.
It is the output. (paginate is for 5 items per page and total no of entry is 7 in my case)
Page 1
Page 2
Can anyone help me please?
Thanks in advance for helping.
just make a small change in the code and laravel will take care of the rest.
public function getSpecials()
{
$title = "Specials";
$info = DB::table(DB::raw('`car` , `available_car`, `users`'))
->select('car.car_maker', 'car.car_model', 'available_car.car_price', 'car.car_production_year', 'available_car.car_id', 'available_car.id', 'available_car.current_position')
->where('available_car.car_id', '`car`.`car_id`')
->where('available_car.is_sold', 'no')
->whereRaw('`available_car`.`created_at` BETWEEN NOW() - INTERVAL 30 DAY AND NOW()')
->orderByRaw('WEEK(`available_car`.`created_at`) DESC')
->orderBy('available_car.car_price', 'desc')
->orderBy('users.last_paid_date', 'desc')
->orderBy('available_car.created_at', 'desc')
->distinct()
->paginate(5);
return View::make('specials',['info' => $info, 'title' => $title]);
}
in view:
Iterate like this:
#if(!$info->isEmpty())
#foreach($info as $i)
do whatever you want
#endforeach
#else
no data to show....
#endif
{{$info->links()}}
You need to create your paginator manually (Check this question for more details):
$pageNumber = Input::get('page', 1);
$perPage = 5;
$info = DB::table(DB::raw('`car` , `available_car`, `users`'))
->select('car.car_maker', 'car.car_model', 'available_car.car_price', 'car.car_production_year', 'available_car.car_id', 'available_car.id', 'available_car.current_position')
->where('available_car.car_id', '`car`.`car_id`')
->where('available_car.is_sold', 'no')
->whereRaw('`available_car`.`created_at` BETWEEN NOW() - INTERVAL 30 DAY AND NOW()')
->orderByRaw('WEEK(`available_car`.`created_at`) DESC')
->orderBy('available_car.car_price', 'desc')
->orderBy('users.last_paid_date', 'desc')
->orderBy('available_car.created_at', 'desc')
->distinct()
->get();
$slice = array_slice($info, $perpage * ($pageNumber - 1), $perpage);
$info = Paginator::make($slice, count($info), $perPage);
return View::make('specials',['info' => $info, 'title' => $title]);
Then print results in a foreach loop like suggested by #itachi.