Laravel 5分页链接到错误的地方

时间:2015-03-31 19:09:10

标签: php laravel-5 laravel-pagination

我目前正在从4.2中将我的一个项目更新到Laravel 5。我知道很多东西已经改变了paginator类,但我真的无法弄清楚为什么这不起作用。我在我项目中多个位置的雄辩模型上调用paginate(),每个东西都很棒。

但是这个项目有一个带有过滤器的配置文件搜索页面,所以我必须调用一个巨大的自定义DB :: table()查询。之后我想从结果中构建一个paginator对象。

$q = \DB:: HUGE QUERY HERE....

// Execute query
$results = $q->get();

// Get pagination information and slice the results.
$perPage = 20;
$total = count($results);
$start = (Paginator::resolveCurrentPage() - 1) * $perPage;
$sliced = array_slice($results, $start, $perPage);

// Eager load the relation.
$collection = Profile::hydrate($sliced);
$collection->load(['sports', 'info', 'profileImage']);

// Create a paginator instance.
$profiles = new Paginator($collection->all(), $total, $perPage);

return $profiles;

我的问题是,调用$profiles->render()后生成的链接会链接到我项目的根目录而不是当前页面。

实施例: 这些链接位于mysite.com/profiles,但链接到mysite.com/?page=2而不是mysite.com/profiles?page=2

我的代码在Laravel 4.2中运行良好,下面链接以供参考:

工作的Laravel 4.2代码

$q = \DB:: HUGE QUERY HERE....

// Execute query
$results = $q->get();

// Get pagination information and slice the results.
$perPage = 20;
$total = count($results);
$start = (Paginator::getCurrentPage() - 1) * $perPage;
$sliced = array_slice($results, $start, $perPage);

// Eager load the relation.
$collection = Profile::hydrate($sliced);
$collection->load(['sports', 'info', 'profileImage']);

// Create a paginator instance.
$profiles = Paginator::make($collection->all(), $total, $perPage);

return $profiles;

欢迎任何帮助。 谢谢!

2 个答案:

答案 0 :(得分:11)

我终于在工作了几个小时后解决了这个问题!

我发现你可以将路径传递给paginator。 正如您所看到的,这可以通过在构建paginator对象时将数组作为第5个参数传递来完成。此数组将覆盖您传递的任何选项。我们需要覆盖path选项。我正在使用Paginator::resolveCurrentPath()获取当前路径。

所以我的代码现在看起来像:

// Create a paginator instance.
$profiles = new Paginator($collection->all(), $total, $perPage, Paginator::resolveCurrentPage(), [
    'path' => Paginator::resolveCurrentPath()
]);

对于感兴趣的人,paginator构造函数如下所示:

__construct($items, $total, $perPage, $currentPage = null, array $options = [])

你需要手动传递这个很奇怪,我认为这是一个错误。

答案 1 :(得分:0)

如果这对你有用,我不会抱怨。我们在ORM和模型加载方面有不同的方法,但我希望这会给你一些见解。

初始网址

localhost/application-name/public/publishers/?page=1

控制器

class PublisherController extends Controller {
    public function index()
    {
        $publ = Publisher::paginate(5);
        $publ->setPath(''); //I just use custom Url and set path to ''
        return view('publisher-table', ['publishers'=>$publ]);
    }

视图

<div class="row">
{!! $publishers->render() !!}
</div>

生成的网址

localhost/application-name/public/publishers?page=1

我认为不同的服务器配置和方法需要不同的方法。对于我自己,我的开发服务器受到仅由文件夹分隔的项目的污染。所以,这个解决方案就足够了。

有一次,我读过您可以通过将DocumentRoot设置为Laravel public文件夹来解决此问题。但是,不需要为每个开发环境配置虚拟主机。