思路,在博客开发过程中有的时候希望将来自不同模型的数据合并到一个数组中并以分页形式输出,这样既能节省时间也能加大博客首页的更新力度。接下来我们来开始写代码吧!
因为我们在开发过程中需要用到合并数组和分页,我们需要在控制器中引入数组门脸与分页门脸。
第一步引入功能门脸:
use Illuminate\Support\Arr;
use Illuminate\Pagination\LengthAwarePaginator;
use Illuminate\Pagination\Paginator;
第二步先分别获取两个模型中的数据:
$articles = Article::query()->orderBy('id','desc')->withCount(['comments','zans'])->get();
$coursefestival = CourseFestival::query()->where(['status'=>true])->orderBy('id','desc')->limit(5)->get();
withCount(['comments','zans'])
为获取关联模型数据,如果不需要则删除。
第三步合并数组到
$Array
数组中:
$Array = Arr::collapse([$coursefestival, $articles]);
第四步写入分页代码
$perPage = 20; //每页显示数量
if ($request->has('page')) {
$current_page = $request->input('page');
$current_page = $current_page <= 0 ? 1 :$current_page;
} else {
$current_page = 1;
$item = array_slice($Array, ($current_page-1)*$perPage, $perPage);//$Array为要分页的数组
$totals = count($Array);
$paginator =new LengthAwarePaginator($item, $totals, $perPage, $current_page, [
'path' => Paginator::resolveCurrentPath(),
'pageName' => 'page',
return view('themes.default.index',['articles' => $paginator]);
注释:
$perPage
为每页显示数量,
$Array
为要分页的数组,
$totals
为统计数组信息条数,
$paginator
为加入分页后的数组变量。
全部代码:
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Arr;
use Illuminate\Pagination\LengthAwarePaginator;
use Illuminate\Pagination\Paginator;
use App\Models\Article;
use App\Models\CourseFestival;
class IndexController extends Controller
public function index(Request $request)
$articles = Article::query()->orderBy('id','desc')->withCount(['comments','zans'])->get();
$coursefestival = CourseFestival::query()->where(['status'=>true])->orderBy('id','desc')->limit(5)->get();
$Array = Arr::collapse([$coursefestival, $articles]);
$perPage = 20; //每页显示数量
if ($request->has('page')) {
$current_page = $request->input('page');
$current_page = $current_page <= 0 ? 1 :$current_page;
} else {
$current_page = 1;
$item = array_slice($Array, ($current_page-1)*$perPage, $perPage);//$Array为要分页的数组
$totals = count($Array);
$paginator =new LengthAwarePaginator($item, $totals, $perPage, $current_page, [
'path' => Paginator::resolveCurrentPath(),
'pageName' => 'page',
$courses = CourseBasic::query()->where('status',true)->limit(5)->get();
$hotarticles = Article::query()->orderBy('view_count','desc')->limit(9)->get();
$codes=Code::query()->orderBy('created_at','desc')->limit(9)->get();
return view('default.index',['articles' => $paginator]);