Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Laravel Pages Laravel Package

binetvn/laravel-pages

Simple pages manager for Laravel applications. Provides basic structure to create and manage site pages, intended for quick setup of static or CMS-like content within a Laravel project.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require binetvn/laravel-pages
    php artisan vendor:publish --provider="Binetvn\Pages\PagesServiceProvider" --tag="pages-config"
    php artisan migrate
    
    • Publishes the migration and config file to config/pages.php.
  2. First Use Case:

    • Create a page via Tinker or a controller:
      use Binetvn\Pages\Models\Page;
      
      $page = Page::create([
          'title' => 'About Us',
          'slug' => 'about',
          'content' => '<h1>Welcome to our page!</h1>',
          'is_published' => true,
      ]);
      
    • Display the page in a Blade template:
      @foreach(\Binetvn\Pages\Models\Page::published()->get() as $page)
          <h2><a href="{{ route('pages.show', $page->slug) }}">{{ $page->title }}</a></h2>
          {!! $page->content !!}
      @endforeach
      
  3. Routing:

    • Add the route in routes/web.php:
      Route::get('/pages/{slug}', [\Binetvn\Pages\Http\Controllers\PageController::class, 'show'])->name('pages.show');
      

Implementation Patterns

Workflows

  1. CRUD Operations:

    • Use the Page model for all CRUD operations (e.g., Page::find(1)->update(['content' => '...'])).
    • Leverage Eloquent relationships if extending the model (e.g., Page::with('author')->get()).
  2. Content Management:

    • Store rich content (HTML, Markdown) in the content field. Use a package like spatie/laravel-medialibrary for file attachments if needed.
    • Example: Add a meta_description field to the pages table and update the model:
      $page->meta_description = 'SEO-friendly description';
      $page->save();
      
  3. Dynamic Page Rendering:

    • Use Blade directives or helpers to render pages dynamically:
      // In a controller
      public function show(Page $page)
      {
          return view('pages.show', compact('page'));
      }
      
    • Extend the PageController to customize behavior (e.g., caching, redirects).
  4. Pagination:

    • Fetch paginated pages:
      $pages = Page::published()->paginate(10);
      
  5. Localization:

    • Add locale and content fields to a pivot table (e.g., page_translations) if supporting multilingual content. Override the Page model to handle translations.

Integration Tips

  1. Middleware:

    • Protect unpublished pages with middleware:
      Route::get('/pages/{slug}', [PageController::class, 'show'])
           ->middleware('pages.published')
           ->name('pages.show');
      
    • Create custom middleware:
      namespace App\Http\Middleware;
      use Closure;
      use Binetvn\Pages\Models\Page;
      
      class CheckPageExists
      {
          public function handle($request, Closure $next, $slug)
          {
              if (!Page::where('slug', $slug)->exists()) {
                  abort(404);
              }
              return $next($request);
          }
      }
      
  2. Events:

    • Listen for page creation/publishing:
      // In EventServiceProvider
      protected $listen = [
          'Binetvn\Pages\Events\PageCreated' => [
              'App\Listeners\NotifyPageCreated',
          ],
      ];
      
  3. API Endpoints:

    • Expose pages via API:
      Route::apiResource('pages', \Binetvn\Pages\Http\Controllers\Api\PageController::class)->only(['index', 'show']);
      
  4. Admin Panel:

    • Integrate with admin panels (e.g., Nova, Filament) by extending the Page resource:
      // For Laravel Nova
      Nova::resources([
          \Binetvn\Pages\Nova\Page::class,
      ]);
      

Gotchas and Tips

Pitfalls

  1. Slug Conflicts:

    • Ensure slugs are unique. Override the Page model to auto-generate slugs from titles:
      protected static function boot()
      {
          parent::boot();
          static::creating(function ($page) {
              $page->slug = Str::slug($page->title);
          });
      }
      
  2. Content Security:

    • Sanitize user-generated content to prevent XSS. Use Purifier or HTML Purifier:
      $cleanContent = Purifier::clean($page->content);
      
  3. Performance:

    • Avoid eager-loading unnecessary relationships. Use with() selectively:
      // Bad: Page::with('author', 'tags')->get();
      // Good: Page::with('author')->get();
      
  4. Migration Conflicts:

    • If the pages table already exists, manually adjust the migration or use:
      php artisan migrate --path=/vendor/binetvn/laravel-pages/database/migrations
      
  5. Caching:

    • Cache published pages to reduce database load:
      $page = Cache::remember("page:{$slug}", now()->addHours(1), function () use ($slug) {
          return Page::where('slug', $slug)->firstOrFail();
      });
      

Debugging

  1. Query Logs:

    • Enable query logging to debug slow queries:
      DB::enableQueryLog();
      Page::published()->get();
      dd(DB::getQueryLog());
      
  2. Model Events:

    • Debug model events by listening to them temporarily:
      Page::created(function ($page) {
          \Log::info('Page created:', ['id' => $page->id]);
      });
      
  3. Route Debugging:

    • Use php artisan route:list to verify routes are registered correctly.

Extension Points

  1. Custom Fields:

    • Extend the pages table with custom fields (e.g., template, layout). Update the model:
      protected $fillable = ['title', 'slug', 'content', 'is_published', 'template'];
      
  2. Page Templates:

    • Implement a template system by adding a template field and using Blade includes:
      @if($page->template === 'hero')
          @include('pages.templates.hero', ['page' => $page])
      @else
          {!! $page->content !!}
      @endif
      
  3. Soft Deletes:

    • Enable soft deletes for pages:
      use Illuminate\Database\Eloquent\SoftDeletes;
      
      class Page extends Model
      {
          use SoftDeletes;
          protected $dates = ['deleted_at'];
      }
      
    • Update migrations and routes to handle soft-deleted pages.
  4. Policy Integration:

    • Restrict page access with policies:
      use Binetvn\Pages\Models\Page;
      use App\Models\User;
      
      class PagePolicy
      {
          public function view(User $user, Page $page)
          {
              return $page->is_published || $user->isAdmin();
          }
      }
      
    • Register the policy in AuthServiceProvider.
  5. Testing:

    • Write feature tests for page creation and rendering:
      public function test_page_creation()
      {
          $response = $this->post('/admin/pages', [
              'title' => 'Test Page',
              'slug' => 'test',
              'content' => '<p>Hello</p>',
          ]);
          $response->assertRedirect();
          $this->assertDatabaseHas('pages', ['slug' => 'test']);
      }
      
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
facebook/capi-param-builder-php
babelqueue/symfony
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle
atriumphp/atrium
sandermuller/package-boost-laravel
sandermuller/boost-skills
redaxo/core
yusufgenc/filament-api-forge