php Laravel 分页漂亮的 URL

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20974404/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 03:42:56  来源:igfitidea点击:

Laravel pagination pretty URL

phplaravellaravel-4

提问by jOpacic

Is there a way to get a pagination pretty URL in Laravel 4?

有没有办法在 Laravel 4 中获得分页漂亮的 URL?

For example, by default:

例如,默认情况下:

http://example.com/something/?page=3

And what I would like to get:

我想得到的是:

http://example.com/something/page/3

Also, the pagination should render this way, and appending to the pagination should appear in this way.

此外,分页应该以这种方式呈现,并且附加到分页应该以这种方式出现。

采纳答案by bitlather

Here's a hacky workaround. I am using Laravel v4.1.23. It assumes page number is the last bit of your url. Haven't tested it deeply so I'm interested in any bugs people can find. I'm even more interested in a better solution :-)

这是一个hacky解决方法。我正在使用 Laravel v4.1.23。它假定页码是您网址的最后一位。尚未对其进行深入测试,因此我对人们可以找到的任何错误感兴趣。我对更好的解决方案更感兴趣:-)

Route:

路线:

Route::get('/articles/page/{page_number?}', function($page_number=1){
    $per_page = 1;
    Articles::resolveConnection()->getPaginator()->setCurrentPage($page_number);
    $articles = Articles::orderBy('created_at', 'desc')->paginate($per_page);
    return View::make('pages/articles')->with('articles', $articles);
});

View:

看法:

<?php
    $links = $articles->links();
    $patterns = array();
    $patterns[] = '/'.$articles->getCurrentPage().'\?page=/';
    $replacements = array();
    $replacements[] = '';
    echo preg_replace($patterns, $replacements, $links);
?>

Model:

模型:

<?php
class Articles extends Eloquent {
    protected $table = 'articles';
}

Migration:

移民:

<?php

use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateArticlesTable extends Migration {

    public function up()
    {
        Schema::create('articles', function($table){
            $table->increments('id');
            $table->string('slug');
            $table->string('title');
            $table->text('body');
            $table->timestamps();
        });
    }

    public function down()
    {
        Schema::drop('articles');
    }
}

回答by Marcin Nabia?ek

It's possible but you need to code a bit.

这是可能的,但您需要编写一些代码。

First you need to change in app/config/app.phppagination service provider - you need to write your own.

首先,您需要更改app/config/app.php分页服务提供商 - 您需要自己编写。

Comment:

评论:

// 'Illuminate\Pagination\PaginationServiceProvider',

and add

并添加

'Providers\PaginationServiceProvider',

in providers section.

在提供者部分。

Now you need to create your PaginationServiceProvider to use custom pagination factory:

现在您需要创建您的 PaginationServiceProvider 以使用自定义分页工厂:

model/Providers/PaginationServiceProvider.phpfile:

model/Providers/PaginationServiceProvider.php文件:

<?php

namespace Providers;

use Illuminate\Support\ServiceProvider;

class PaginationServiceProvider extends ServiceProvider
{

    /**
     * Indicates if loading of the provider is deferred.
     *
     * @var bool
     */
    protected $defer = true;

    /**
     * Register the service provider.
     *
     * @return void
     */
    public function register()
    {
        $this->app->bindShared('paginator', function ($app) {
            $paginator = new PaginationFactory($app['request'], $app['view'],
                $app['translator']);

            $paginator->setViewName($app['config']['view.pagination']);

            $app->refresh('request', $paginator, 'setRequest');

            return $paginator;
        });
    }

    /**
     * Get the services provided by the provider.
     *
     * @return array
     */
    public function provides()
    {
        return array('paginator');
    }

}

Above you create Providers\PaginationFactoryobject, so now we need to create this file:

在上面创建Providers\PaginationFactory对象,所以现在我们需要创建这个文件:

model/providers/PaginationFactory.phpfile:

model/providers/PaginationFactory.php文件:

<?php


namespace Providers;

use Illuminate\Pagination\Factory;


class PaginationFactory extends  Factory {

    /**
     * Get a new paginator instance.
     *
     * @param  array  $items
     * @param  int    $total
     * @param  int|null  $perPage
     * @return \Illuminate\Pagination\Paginator
     */
    public function make(array $items, $total, $perPage = null)
    {
        $paginator = new \Utils\Paginator($this, $items, $total, $perPage);

        return $paginator->setupPaginationContext();
    }        
} 

Here you create only \Utils\Paginatorobject so now let's create it:

在这里你只创建\Utils\Paginator对象,所以现在让我们创建它:

model/Utils/Paginator.phpfile:

model/Utils/Paginator.php文件:

<?php

namespace Utils;



class Paginator extends \Illuminate\Pagination\Paginator {


    /**
     * Get a URL for a given page number.
     *
     * @param  int  $page
     * @return string
     */
    public function getUrl($page)
    {
      $routeParameters = array();

      if ($page > 1) { // if $page == 1 don't add it to url
         $routeParameters[$this->factory->getPageName()] = $page;
      }

      return \URL::route($this->factory->getCurrentUrl(), $routeParameters);
    }
}

In this file we finally override default method for creating pagination urls.

在这个文件中,我们最终覆盖了创建分页网址的默认方法。

Let's assume you have route defined this way:

让我们假设您以这种方式定义了路由:

Route::get('/categories/{page?}',
    ['as'   => 'categories',
     'uses' => 'CategoryController@displayList'
    ])->where('page', '[1-9]+[0-9]*');

As you see we defined here route name using as(it's important because of Paginator implementation above - but you can do it of course in different way).

正如您所看到的,我们在这里定义了路由名称as(这很重要,因为上面的分页器实现 - 但您当然可以以不同的方式来实现)。

Now in method displayListof CategoryControllerclass you can do:

现在在类的方法中displayListCategoryController您可以执行以下操作:

public function displayList($categories, $page = 1) // default 1 is needed here 
{
    Paginator::setCurrentPage($page);
    Paginator::setBaseUrl('categories'); // use here route name and not the url
    Paginator::setPageName('page');

    $categories = Category::paginate(15);


    return View::make('admin.category')->with(
        ['categories' => $categories]
    );
}

When in your view you add:

在您的视图中添加:

<?php echo $categories->links(); ?>

you will get generated urls this way:

您将通过以下方式获得生成的网址:

http://localhost/categories
http://localhost/categories/2
http://localhost/categories/3
http://localhost/categories/4
http://localhost/categories/5

without ? in query string

没有 ?在查询字符串中

However in my opinion something like this should be added by default or at least it should be enough to extend one class and not to create 3 classes just to implement one method.

但是,在我看来,应该默认添加这样的东西,或者至少应该足以扩展一个类,而不是仅仅为了实现一种方法而创建 3 个类。

回答by Felice Ostuni

hope this is helpful for someone, I've made a trait to be used in models. The idea is that this custom method can detect current route and adjust links to use correct segment position for {page} parameter:

希望这对某人有帮助,我已经制作了一个可用于模型的特征。这个想法是这个自定义方法可以检测当前路线并调整链接以使用{page}参数的正确段位置:

https://gist.github.com/zofe/ced0054e6ac6eff1ea95

https://gist.github.com/zofe/ced0054e6ac6eff1ea95

回答by Aki W

For anyone that is using laravel version 5.6+

对于使用 laravel 5.6+ 版的任何人

You can pass additional parameters to set the page number.

您可以传递其他参数来设置页码。

According to: https://laravel.com/api/5.6/Illuminate/Database/Eloquent/Builder.html#method_paginate

根据:https: //laravel.com/api/5.6/Illuminate/Database/Eloquent/Builder.html#method_paginate

Example:

例子:

StoreController.php

商店控制器.php

/**
 * Show sale item based on given page
 *
 * @param int $page
 * @return \Illuminate\Http\Response
 */
public function showPage($page = 1)
{
    $saleItems = SaleItem::paginate(10, array('*'), 'page', $page);

    ...
}

Then, in your blade template. You can just route( ... , array('page' => $page));

然后,在您的刀片模板中。你可以route( ... , array('page' => $page));

回答by Elman Huseynov

For Laravel 5.8 use this solution in blade.php where you generate links:

对于 Laravel 5.8,在您生成链接的blade.php 中使用此解决方案:

    $links = $data->links(); 
    $patterns = '#\?page=#';

    $replacements = '/page/';
    $one = preg_replace($patterns, $replacements, $links);

    $pattern2 = '#page/([1-9]+[0-9]*)/page/([1-9]+[0-9]*)#';
    $replacements2 = 'page/';
    $paginate_links = preg_replace($pattern2, $replacements2, $one);
    echo $paginate_links;

回答by Mike Rockétt

The only way I can think of doing this is by extending the Paginator class to do the matching. However, just know that it may conflict with third-party packages and other classes/libraries. The current method is designed to work with nearly all classes/libraries/packages.

我能想到的唯一方法是扩展 Paginator 类来进行匹配。但是,只知道它可能与第三方包和其他类/库冲突。当前方法旨在与几乎所有类/库/包一起使用。

Perhaps you could try the following:

也许您可以尝试以下操作:

http://packalyst.com/packages/package/desmart/pagination('pagination' by 'desmart')

http://packalyst.com/packages/package/desmart/pagination('desmart' 的'分页')