In web applications, pagination is an essential feature for managing large datasets. Laravel provides robust pagination tools out of the box, but making pagination limits configurable adds flexibility. This tutorial will guide you through building a dynamic, database-driven pagination system where the number of items per page can be adjusted without modifying the code.
Scenario: Configurable Pagination
Imagine you’re building an e-commerce application or a blog where:
- Admins want to control the number of products or posts displayed per page.
- Pagination limits (e.g., 10, 20, or 50 items per page) should be adjustable dynamically from a database-driven configuration.
We’ll create a system to manage pagination settings dynamically.
Step 1: Create a Settings Table and Model
Start by setting up a table to store configuration settings.
- Generate the Migration:
php artisan make:migration create_settings_table --create=settings
- Define the Schema:
Open the generated migration file and define a key-value structure:
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateSettingsTable extends Migration
{
public function up()
{
Schema::create('settings', function (Blueprint $table) {
$table->id();
$table->string('key')->unique();
$table->string('value')->nullable();
$table->timestamps();
});
}
public function down()
{
Schema::dropIfExists('settings');
}
}
- Run the Migration:
php artisan migrate
- Create the Model:
Generate the model:
php artisan make:model Setting
Define the model in app/Models/Setting.php:
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Setting extends Model
{
protected $fillable = ['key', 'value'];
}
Step 2: Seed the Database with Pagination Settings
Add an initial pagination limit for testing.
- Create a Seeder:
php artisan make:seeder SettingsSeeder
- Add Pagination Limit to the Seeder:
Open the seeder file and define a default pagination limit:
namespace Database\Seeders;
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\DB;
class SettingsSeeder extends Seeder
{
public function run()
{
DB::table('settings')->insert([
['key' => 'pagination_limit', 'value' => '10'],
]);
}
}
- Run the Seeder:
Populate the settings table:
php artisan db:seed --class=SettingsSeeder
Step 3: Create a Helper Function to Retrieve Settings
To fetch the pagination limit dynamically, create a helper function.
- Add the Helper Function:
Create or edit app/Helpers/helpers.php and add the following:
use Illuminate\Support\Facades\Cache;
if (!function_exists('getSetting')) {
function getSetting($key, $default = null)
{
return Cache::rememberForever("setting_{$key}", function () use ($key, $default) {
$setting = \App\Models\Setting::where('key', $key)->first();
return $setting ? $setting->value : $default;
});
}
}
- Load the Helper File:
Add the helper file to composer.json under autoload:
"autoload": {
"files": [
"app/Helpers/helpers.php"
]
}
- Reload Autoload Files:
composer dump-autoload
Step 4: Use Configurable Pagination in Controllers
Now use the getSetting function to fetch the pagination limit dynamically.
- Modify a Controller:
Open any controller where pagination is used. For example:
namespace App\Http\Controllers;
use App\Models\Post;
class PostController extends Controller
{
public function index()
{
$paginationLimit = getSetting('pagination_limit', 10);
$posts = Post::paginate($paginationLimit);
return view('posts.index', compact('posts'));
}
}
- If no database setting is found, the default value of
10is used.
- Dynamic Pagination in Another Example:
Use the same approach for product listings or user lists:
$paginationLimit = getSetting('pagination_limit', 15);
$products = Product::paginate($paginationLimit);
Step 5: Add an Admin Interface for Pagination Settings
Allow admins to update the pagination limit dynamically.
- Create a Settings Controller:
php artisan make:controller Admin/SettingsController
Add methods to edit and update settings:
namespace App\Http\Controllers\Admin;
use App\Models\Setting;
use Illuminate\Http\Request;
class SettingsController extends Controller
{
public function edit()
{
$paginationLimit = Setting::where('key', 'pagination_limit')->value('value');
return view('admin.settings.edit', compact('paginationLimit'));
}
public function update(Request $request)
{
Setting::updateOrCreate(
['key' => 'pagination_limit'],
['value' => $request->input('pagination_limit')]
);
return redirect()->back()->with('success', 'Pagination limit updated successfully.');
}
}
- Create the Blade View:
Create resources/views/admin/settings/edit.blade.php:
- Add Routes:
Define routes for editing and updating settings in routes/web.php:
Route::prefix('admin')->group(function () {
Route::get('settings/edit', [App\Http\Controllers\Admin\SettingsController::class, 'edit'])->name('admin.settings.edit');
Route::put('settings/update', [App\Http\Controllers\Admin\SettingsController::class, 'update'])->name('admin.settings.update');
});
Step 6: Test the Configurable Pagination System
- Update the Pagination Limit:
- Access the admin panel.
- Change the pagination limit (e.g., to 5 or 20).
- Save and reload the page where pagination is applied.
- Verify the Updates:
- Ensure that the number of items per page reflects the updated limit.
Benefits of a Configurable Pagination System
- Flexibility: Admins can adjust the number of items per page dynamically without modifying code.
- User Experience: Tailor pagination to the needs of the application or dataset size.
- Scalability: Easily adapt to changes as your application grows.
Conclusion
You’ve successfully implemented a configurable pagination system in Laravel. By combining database-driven settings with Laravel’s pagination tools, you’ve created a flexible and maintainable solution that adapts to your application’s needs in real time.