When we use paginator, the page URLs look like this

http://localhost/?page=1

But we want URLs like this

http://localhost/page/1

The Laravel 4.2 now is still no support this functions. According to Laravel Paginator Pretty URLs ,I do it myself.

Step 1

I create a new folder named custom_class under my app folder, and then create a new php file named PrettyPaginator.php under custom_class , here is the full code.

setupPaginationContext();
    }

    /**
     * Get a URL for a given page number.
     *
     * @param  int  $page
     * @return string
     */
    public function getUrl($page)
    {
        $pageName = $this->factory->getPageName();

        $parameters = [];

        if (count($this->query) > 0)
        {
            $parameters = array_merge($this->query, $parameters);
        }

        $currentUrl = $this->factory->getCurrentUrl();

        $pageUrl = $currentUrl.'/'.$pageName.'/'.$page;

        if (count($parameters) > 0)
        {
            $pageUrl .= '?'.http_build_query($parameters, null, '&');
        }

        $pageUrl .= $this->buildFragment();

        return $pageUrl;
    }

} 

Step 2

Don't forget add our custom_class to the autoload list. Edit the file app\start\global.php,add our directory into the ClassLoader::addDirectories array, it looks like this
ClassLoader::addDirectories(array(

    app_path().'/commands',
    app_path().'/controllers',
    app_path().'/models',
    app_path().'/database/seeds',
    app_path().'/custom_class',  //here is our custom class directory

)); 

Step 3

The routes.php must have the pretty partten. Attention, use Paginator::getPageName() instand of page, because the default value is page, but the only one.

Route::get(Paginator::getPageName().'/{page}/', array('as' => 'posts.index', 'uses' => 'PostsController@getIndex')); 

My PostsController is

public function getIndex($page = null){

    $perpage = 10;

    if(!isset($page))
    {
        $page = 1;
        $totalItems = 0;
    }

    $posts = Posts::with('Author')->orderBy('id', 'DESC')->take($perpage)->skip(($page-1) * $perpage)->get();

    Paginator::setBaseUrl(Config::get('app.url'));
    Paginator::setCurrentPage($page);
    $totalItems = Posts::with('Author')->count();

    $paginator = PrettyPaginator::make($posts->toArray(), $totalItems, $perpage);

    $views = View::make('defualt.app.index')->with('posts', $posts)->with('paginator', $paginator);

    $this->layout->page_title = 'List page';
    $this->layout->content = $views;

} 

My layout view is

 




	{{$page_title}}

@include('default.app.header')
@yield("content")
@include('default.app.footer')

My index view is

@section("content")
    @foreach($posts as $post)

{{link_to_route('posts.show', $post->title , array($post->id), array('id'));}}

{{$post->content}}

Posted by {{$post->Author->name}} at {{$post->created_at}}

@endforeach {{$paginator->links()}} @stop

有想讨论的,大家可以去我的github repo留言:How to make paginator with pretty URLs