Dynamic content allows you to customize the user experience by tailoring elements such as sidebars, widgets, or page layouts based on site settings. In this tutorial, you’ll learn how to use database-driven settings to control dynamic content rendering in Laravel, enabling real-time adjustments without modifying the codebase.


Scenario: Dynamic Content Customization

Imagine an application where you want to:

  • Toggle the visibility of a sidebar or specific widgets.
  • Control the number of items displayed in a section (e.g., recent posts or featured products).
  • Enable or disable specific content sections dynamically.

We’ll build a system to manage these behaviors using site settings stored in a database.


Step 1: Create a SiteSettings Table and Model

Start by setting up a table to store the content-related settings.

  1. Generate the Migration:

   php artisan make:migration create_site_settings_table --create=site_settings
  1. Define the Schema:

Open the migration file and define the necessary fields:


   use Illuminate\Database\Migrations\Migration;
   use Illuminate\Database\Schema\Blueprint;
   use Illuminate\Support\Facades\Schema;

   class CreateSiteSettingsTable extends Migration
   {
       public function up()
       {
           Schema::create('site_settings', function (Blueprint $table) {
               $table->id();
               $table->string('key')->unique();
               $table->string('value')->nullable();
               $table->timestamps();
           });
       }

       public function down()
       {
           Schema::dropIfExists('site_settings');
       }
   }
  1. Run the Migration:

   php artisan migrate
  1. Create the Model:

Generate and define the SiteSetting model:


   php artisan make:model SiteSetting

   namespace App\Models;

   use Illuminate\Database\Eloquent\Model;

   class SiteSetting extends Model
   {
       protected $fillable = ['key', 'value'];
   }

Step 2: Seed the Database with Content Settings

Add initial content-related settings for testing.

  1. Create a Seeder:

   php artisan make:seeder SiteSettingsSeeder
  1. Define Default Content Settings:

Add settings like sidebar visibility and widget toggles:


   namespace Database\Seeders;

   use Illuminate\Database\Seeder;
   use Illuminate\Support\Facades\DB;

   class SiteSettingsSeeder extends Seeder
   {
       public function run()
       {
           DB::table('site_settings')->insert([
               ['key' => 'sidebar_visible', 'value' => 'true'],
               ['key' => 'featured_products_widget', 'value' => 'true'],
               ['key' => 'recent_posts_widget', 'value' => 'false'],
           ]);
       }
   }
  1. Run the Seeder:

   php artisan db:seed --class=SiteSettingsSeeder

Step 3: Create a Helper to Retrieve Settings

To easily access the settings, create a helper function.

  1. Add the Helper Function:

Create or edit app/Helpers/helpers.php and add:


   use Illuminate\Support\Facades\Cache;

   if (!function_exists('getSetting')) {
       function getSetting($key, $default = null)
       {
           return Cache::rememberForever("site_setting_{$key}", function () use ($key, $default) {
               $setting = \App\Models\SiteSetting::where('key', $key)->first();
               return $setting ? $setting->value : $default;
           });
       }
   }
  1. Load the Helper File:

Add it to composer.json:


   "autoload": {
       "files": [
           "app/Helpers/helpers.php"
       ]
   }

Then run:


   composer dump-autoload

Step 4: Use Dynamic Content Settings in Blade Views

Control content rendering dynamically in your Blade templates.

  1. Example: Sidebar Visibility:

   @if (getSetting('sidebar_visible', 'false') === 'true')
       
   @endif
  1. Example: Widget Toggles:

   @if (getSetting('featured_products_widget', 'false') === 'true')
       

Featured Products

@endif @if (getSetting('recent_posts_widget', 'false') === 'true')

Recent Posts

@endif

Step 5: Use Dynamic Content in Controllers

For more complex dynamic behavior, retrieve settings in controllers.

  1. Example: Dynamic Section Control:

   namespace App\Http\Controllers;

   use Illuminate\Http\Request;

   class PageController extends Controller
   {
       public function index()
       {
           $sidebarVisible = getSetting('sidebar_visible', 'false') === 'true';
           $featuredWidget = getSetting('featured_products_widget', 'false') === 'true';

           return view('pages.index', compact('sidebarVisible', 'featuredWidget'));
       }
   }
  1. Pass Data to Blade Views:

Use the passed variables in your templates:


   @if ($sidebarVisible)
       
   @endif

   @if ($featuredWidget)
       

Featured Products

@endif

Step 6: Add an Admin Interface for Content Settings

Allow admins to manage content-related settings dynamically.

  1. Create a Controller:

   php artisan make:controller Admin/ContentSettingsController

Add methods to edit and update settings:


   namespace App\Http\Controllers\Admin;

   use App\Models\SiteSetting;
   use Illuminate\Http\Request;

   class ContentSettingsController extends Controller
   {
       public function edit()
       {
           $settings = SiteSetting::all();
           return view('admin.content-settings.edit', compact('settings'));
       }

       public function update(Request $request)
       {
           foreach ($request->settings as $key => $value) {
               SiteSetting::updateOrCreate(['key' => $key], ['value' => $value]);
           }

           return redirect()->back()->with('success', 'Content settings updated successfully.');
       }
   }
  1. Create a Blade View:

   
@csrf @method('PUT') @foreach ($settings as $setting)
@endforeach
  1. Define Routes:

Add routes for the admin interface:


   Route::prefix('admin')->group(function () {
       Route::get('content-settings/edit', [App\Http\Controllers\Admin\ContentSettingsController::class, 'edit'])->name('admin.content-settings.edit');
       Route::put('content-settings/update', [App\Http\Controllers\Admin\ContentSettingsController::class, 'update'])->name('admin.content-settings.update');
   });

Benefits of Dynamic Content Settings

  • Flexibility: Adjust content visibility and behavior without modifying code.
  • Customization: Tailor content for users or admin preferences dynamically.
  • Ease of Use: Enable non-technical users to control application behavior through an admin panel.

Conclusion

You’ve now implemented a dynamic content system in Laravel that adapts to site settings stored in the database. With this setup, you can customize sidebars, widgets, and other content sections in real-time, enhancing your application’s flexibility and user experience.