如何使用 laravel 中控制器中的数组变量在视图中进行分页


How to make pagination in view by using the array variable from controller in laravel

我是Laravel的新手,我无法理解从控制器传递到视图的数组的分页概念。

我的视图代码

@foreach($aHotelRooms as $aHotelRoom)
<?php 
    //display contents
?>
@endforeach

在这里,我想使用 $aHotelRooms 设置分页。

我不知道如何使用$users = DB::table('table_name')->paginate(3);echo $users->render();$aHotelRooms..

请有人帮助我..

我不知道如何使用...

paginate(3)将创建集合,其中数据库只有 3 行。然后$users->render();将创建 HTML 分页代码。必须在视图中使用$users->render();。您不需要使用 @foreach 或类似的东西来构建分页。

例:

在控制器中:

$aHotelRooms = AHotelRoom::paginate(10);
return view('myview', compact('aHotelRooms'));

myview.blade.php

$aHotelRooms->render();

我最终得到了这个解决方案。它对我很有用。

控制器

use Illuminate'Pagination'LengthAwarePaginator as Paginator;
use DB;
    public function postHotelresults(Request $request,$page = 1)
    {
    .
    .
    .
    $sqlCond = 'WHERE 1 '.$this->getAreaCondition($_POST['search_city']);
    .
    .
    $query = "SELECT `h`.*,".$countquery.",".$minquery." FROM `abserve_hotels` as `h`";
    $query1 = DB::select($query.$sqlCond);
    $perPage = 2;
    $currentPage = Input::get('page', 1) - 1;
    $pagedData = array_slice($query1, $currentPage * $perPage, $perPage);
    $query1 =  new Paginator($pagedData, count($query1), $perPage);
    $query1->setPath('hotelresults');
    .
    .
    return view('hotel.list', $this->data,compact('query1'));
    }

在这里,setPath('hotelresults')在分页中单击我的链接时指向我的函数

视图

<?php 
if(!empty($query1)){
?>
@foreach($query1 as $aHotelRoom)
{{$aHotelRoom->hotel_id }}
{{$aHotelRoom->logo}}
@endforeach
<?php
echo $query1->render();
}

在这里,我发现了一件事,当我们想从控制器传递数组时,我们应该使用 $query1 = DB::select(...) 来编写查询,并使用return view('hotel.list',compact('query1'));将数组格式的查询传递给视图。

它可能对某人有用...