一尘不染

Laravel分页漂亮的URL

php

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

例如,默认情况下:

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

我想得到的是:

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

同样,分页应以这种方式呈现,并且添加到分页应以这种方式出现。


阅读 341

收藏
2020-05-29

共1个答案

一尘不染

这是一个骇人的解决方法。我正在使用Laravel
v4.1.23。假设页码是您网址的最后一位。还没有进行深入的测试,因此我对人们可以找到的任何bug感兴趣。我对更好的解决方案更感兴趣:-)

路线:

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);
});

视图:

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

模型:

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

移民:

<?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');
    }
}
2020-05-29