我怎样才能获得发送到视图的集合的 Laravel 5.2 分页?

How could I get Laravel 5.2 Pagination for a collection being sent to a view?

我正在使用 Laravel 5.2 并为提要页面使用多态关系 table。提要包含具有各自模型的图片、文章和链接。我用于提要的控制器方法如下所示:

public function index()
{
    $allActivity = Activity::get();

    $activity = collect();

    foreach($allActivity as $act)
    {

        $modelString = $act->actable_type;
        $class = new $modelString();
        $model = $class->find($act->actable_id);

        $activity->push($model);
    }

    return view('feed', compact('activity'));
}

这里是 feed.blade.php 视图

  @foreach($activity as $class)
      // Gives me the model name so the correct partial view could be referenced
      <?php
            $split = explode("\", get_class($class));
            $model = lcfirst($split[1]);
        ?>

      @include("partials.{$model}", [$model => $class])
    @endforeach

由于此设置,我无法使用 Laravel 文档中概述的方法进行分页。我如何使用此设置正确实现分页?任何帮助将不胜感激。

使用您的 Activity 模型上应有的 actable() 关系访问您的关系。它还将帮助您避免像现在这样在循环中使用 find(),这会给您带来 N+1 问题。

在您的 activity 模型中,您应该有一个 actable 方法:

class Activity 
{
    public function actable()
    {
        return $this->morphTo();
    }
}

然后在您的视图中,您可以延迟加载所有多态可执行关系并传递给视图。您甚至可以保持视图整洁并在 map() 函数中解析模型名称:

public function index()
{
    $activity = Activity::with('actable')->get()->map(function($activity) {
        $activity->actable->className = lcfirst(class_basename($activity->actable));
        return $activity->actable;
    });

    return view('feed', compact('activity'));
}

那么在你看来:

@foreach($activity as $model)   
    @include("partials.{$model->className}", [$model->className => $class])
@endforeach

对于 运行 这与分页将是:

控制器:

public function index()
{
    $activities = Activity::with('actable')->paginate(25);

    return view('feed', compact('activities'));
}

查看:

@foreach($activities as $activity)  
    @include('partials.'.lcfirst(class_basename($activity->actable)), [lcfirst(class_basename($activity->actable)) => $activity])
@endforeach