我试图在Laravel中创建一个简单的博客,但我被这个小细节卡住了。我有博客文章,想在主页上显示一些,并在localhost/posts路径上有其他链接。
问题是我不知道如何创建一个链接到主页上分页的帖子,所以分页从主页上最后一篇帖子的结尾开始。
编辑:我希望用户能够点击路线"帖子"并查看所有帖子,甚至是主页上的帖子
示例
localhost/ - has first 3 posts
localhost/posts?page=2 - has the rest starting from 4th post
我试过这样做,但没有用。
路线
Route::get('posts?page={page}', ['as' => 'rest', 'uses' => 'Controller@getRest']);
控制器具有此功能
public function getRest($page) {
Paginator::setCurrentPage($page);
$posts = Post::paginate(3);
return View::make('posts')->with('posts', $posts);
}
我尝试在主页视图模板中创建链接,如下所示:
<a href="{{ URL::route('posts?page={page}', 2) }}">Show the rest of posts</a>
谢谢你的帮助。
这应该可以工作。唯一的问题是,当用户点击主页中的page 2
链接时,用户将看到10个帖子,从第13个帖子开始,而不是第3个帖子。虽然将Controller::posts
中的->skip(3 + ($page - 1) * 10)
更改为->skip(3 + ($page - 2) * 10)
似乎起到了作用,但page 1
链路将失败。
路线
Route::get('/', [ 'as' => 'home', 'uses' => 'Controller@home' ]);
Route::get('posts', [ 'as' => 'posts', 'uses' => 'Controller@posts' ]);
控制器
class Controller extends BaseController {
public function home()
{
$posts = Post::take(3)->get();
$pagination = Paginator::make($posts->toArray(), Post::count(), 10);
$pagination->setBaseUrl(route('posts'));
return View::make('home', compact('posts', 'pagination'));
}
public function posts()
{
// Current page number (defaults to 1)
$page = Input::get('page', 1);
// Get 10 post according to page number, after the first 3
$posts = Post::skip(3 + ($page - 1) * 10)->take(10)->get();
// Create pagination
$pagination = Paginator::make($posts->toArray(), Post::count(), 10);
return View::make('posts', compact('posts', 'pagination'));
}
}
home.blade.php
@foreach ($posts as $post)
{{ $post->title }}
@endforeach
{{ $pagination->links() }}