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

Site Laravel Package

laravel-admin/site

Laravel package that adds a “site” singleton to the service container for storing app-wide data (supports dot notation). Includes defaults via config, can populate values from a model, and shares the container with all views as $site.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require laravel-admin/site
    

    Add the service provider to config/app.php:

    LaravelAdmin\Site\SiteServiceProvider::class,
    
  2. Publish Config:

    php artisan vendor:publish --tag="site"
    

    This provides default configuration and a basic structure.

  3. First Use Case: Set a global site title in a controller or service:

    app('site')->set('title', 'My Awesome Website');
    

    Access it in any view via $site:

    <title>{{ $site->get('title') }}</title>
    

Implementation Patterns

Core Workflow

  1. Centralized Data Storage: Use the container to store reusable data (e.g., site metadata, settings, or dynamic content) that spans multiple views or controllers.

    // Set SEO metadata globally
    app('site')->set('seo.title', 'Page Title');
    app('site')->set('seo.description', 'Page Description');
    
  2. Model Integration: Automatically populate the container from Eloquent models (e.g., a Page model with title, description, content):

    $page = Page::find(1);
    app('site')->model($page); // Fills 'title', 'description', 'content' keys
    
  3. View Access: Pass the container to views via $site (automatically shared). Use dotted notation for nested data:

    <meta name="description" content="{{ $site->get('seo.description') }}">
    
  4. Dynamic Content: Update the container in middleware or controllers to reflect user-specific or request-based data:

    // Middleware: Set user-specific footer
    app('site')->set('footer.copyright', '© ' . now()->year . ' ' . auth()->user()->name);
    

Advanced Patterns

  • Configuration Overrides: Extend the published config to define default values or validation rules for container keys.

    // config/site.php
    'defaults' => [
        'title' => 'Default Title',
        'seo' => [
            'title' => 'Default SEO Title',
            'description' => 'Default SEO Description',
        ],
    ],
    
  • Service Layer Abstraction: Create a dedicated service class to encapsulate container logic (e.g., SiteSettingsService) for better testability and reusability.

    class SiteSettingsService {
        public function __construct() {
            $this->site = app('site');
        }
    
        public function setSeo(string $title, string $description) {
            $this->site->set('seo.title', $title);
            $this->site->set('seo.description', $description);
        }
    }
    
  • View Composers: Use view composers to initialize the container with data specific to certain views or layouts:

    View::composer('layouts.app', function ($view) {
        $view->site->set('layout.sidebar', true);
    });
    

Gotchas and Tips

Pitfalls

  1. Singleton Scope: The container is a singleton. Changes persist across requests, so avoid storing request-specific or user-specific data unless explicitly managed (e.g., via middleware).

    • Fix: Use middleware to reset or update the container per request if needed.
  2. No Built-in Validation: The package does not validate container keys or values. Manually validate data before setting it to avoid runtime errors.

    • Tip: Use Laravel’s Validator or custom methods to sanitize inputs:
      $title = Validator::make(['title' => $request->title], ['title' => 'required|string|max:255'])->validate();
      app('site')->set('title', $title['title']);
      
  3. Model Integration Assumptions: The model() method assumes the model has title, description, and content attributes. Customize this behavior by extending the service provider or overriding the method.

    • Tip: Extend the SiteServiceProvider to add support for custom model attributes:
      $this->app->extend('site', function ($site) {
          $site->setModelAttributes = function ($model, $attributes = ['title', 'description', 'content']) {
              foreach ($attributes as $attr) {
                  if ($model->$attr) $site->set($attr, $model->$attr);
              }
          };
          return $site;
      });
      
  4. View Variable Overrides: The $site variable is shared globally. Overriding it in a view or layout can lead to unexpected behavior if not managed carefully.

    • Tip: Use view composers or service classes to control initialization.
  5. Performance: Avoid heavy operations (e.g., database queries) when setting container values in middleware or service providers, as they run on every request.

    • Tip: Cache frequently used container values or lazy-load them.

Debugging Tips

  1. Inspect Container Contents: Dump the container in a view or Tinker to debug:

    dd(app('site')->all());
    
  2. Check Config: Ensure the published config (config/site.php) is correctly set up, especially if defaults are not applying.

  3. Middleware Order: If container values are not updating as expected, verify the order of middleware in app/Http/Kernel.php. Middleware that sets container values should run early.

Extension Points

  1. Custom Container Logic: Extend the SiteServiceProvider to add methods or modify existing behavior:

    // app/Providers/SiteServiceProviderExtension.php
    use LaravelAdmin\Site\SiteServiceProvider;
    
    class SiteServiceProviderExtension extends SiteServiceProvider {
        public function register() {
            parent::register();
            $this->app->extend('site', function ($site) {
                $site->addMethod('setCustom', function ($key, $value) {
                    // Custom logic
                });
                return $site;
            });
        }
    }
    
  2. View Helpers: Create a facade or helper to simplify access in views:

    // app/Helpers/SiteHelper.php
    if (!function_exists('site')) {
        function site($key = null, $default = null) {
            $site = app('site');
            return $key ? $site->get($key, $default) : $site;
        }
    }
    

    Usage in views:

    <title>{{ site('title') }}</title>
    
  3. Event-Based Updates: Trigger events when the container is updated to react dynamically (e.g., cache invalidation, analytics tracking):

    // In SiteServiceProvider
    Event::listen('site.updated', function ($key, $value) {
        Cache::forget("site.{$key}");
    });
    
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.
althinect/enum-permission
andydefer/laravel-actions
aimeos/prisma
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky
spatie/mailcoach-vapor