Laravel 4 pagination not working links are OK but

2019-07-20 01:56发布

问题:

In a fresh installation with composer of Laravel 4 in windows 7 I have in routes.php:

Route::model('work', 'Work');
Route::get('/', function()
{
    $works = Work::all();
    $allWorks = Work::paginate(5);

    return View::make('hello', compact('works', 'allWorks'));
 });

And in view file 'hello.php':

<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Laravel PHP Framework</title>
</head>
  <body>
    <div class="container">
        <?php foreach ($works as $work) 
    {
       echo $work->title . '<br/>';
    } 
    ?>
</div>
<?php echo $allWorks->links(); ?>
   </body>
 </html>

I have a database with 25 entries. When I navigate to '/' route I see ALL 25 results of the database (all $work-title fields) and at the bottom the pagination links. When I click on a pagination link the url changes correctly to localhost/laravel/public/?page=1 ... page=2 etc but always showing ALL 25 results. When I change the pagination number eg $allWorks = work::paginate(7); the links change appropriately. I think I have done it exactly as in the documentation but obviously I'm missing something. By googling I saw that .htaccess interferes sometimes with pagination. Here is mine:

<IfModule mod_rewrite.c>
<IfModule mod_negotiation.c>
    Options -MultiViews
</IfModule>

RewriteEngine On

# Redirect Trailing Slashes...
RewriteRule ^(.*)/$ /$1 [L,R=301]

# Handle Front Controller...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [L]
</IfModule>

I don't understand the regex (neither the other stuff in it) but I have commented it out and nothing seemed to change. Can anyone help? Thanks

I also have a model Work.php:

<?php
Class Work extends Eloquent
{
 }

回答1:

You are sending both results to the view, use the following line in routes.php:

return View::make('hello')->with('allWorks', $allWorks);

And this on the View (note the variable used in this line <?php foreach ($allWorks as $work)) :

'hello.php':

<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Laravel PHP Framework</title>
</head>
  <body>
    <div class="container">
        <?php foreach ($allWorks as $work) 
    {
       echo $work->title . '<br/>';
    } 
    ?>
</div>
<?php echo $allWorks->links(); ?>
   </body>
 </html>