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 Base Laravel Package

schaefersoft/laravel-base

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require schaefersoft/laravel-base
    

    Publish the package's assets (if needed) via:

    php artisan vendor:publish --provider="Schaefersoft\LaravelBase\LaravelBaseServiceProvider" --tag="config"
    
  2. First Use Case:

    • Form Generation: Use the FormGenerator to quickly scaffold forms in Blade:
      use Schaefersoft\LaravelBase\Useful\FormGenerator;
      
      FormGenerator::make('user', 'POST', route('users.store'))
          ->addText('name')
          ->addEmail('email')
          ->submit('Create User');
      
    • Searchable Scopes: Apply the Searchable trait to Eloquent models for dynamic search queries:
      use Schaefersoft\LaravelBase\Scopes\Searchable;
      
      class User extends Model
      {
          use Searchable;
      }
      
      Then query with:
      User::search(['name' => 'John', 'email' => 'test@example.com'])->get();
      
  3. Blade Components: Check the resources/views/vendor/laravel-base directory (auto-published) for reusable components like alert, button, or card.


Implementation Patterns

Common Workflows

1. Dynamic Form Handling

  • Pattern: Use FormGenerator for CRUD forms with minimal boilerplate.
    // In a controller:
    $form = FormGenerator::make('product', 'PUT', route('products.update', $product))
        ->addText('name', $product->name)
        ->addSelect('category_id', Category::pluck('name', 'id'), $product->category_id)
        ->method('PUT')
        ->submit('Update');
    
  • Blade Integration:
    {!! $form !!}
    
  • Validation: Pair with Laravel's built-in validation (e.g., FormGenerator::validate()).

2. Search Functionality

  • Pattern: Extend the Searchable trait for reusable search logic across models.
    // Model:
    class Post extends Model
    {
        use Searchable;
    
        protected $searchable = ['title', 'content']; // Fields to search
    }
    
  • Query Builder:
    // Controller:
    $posts = Post::search(request()->query())->paginate(10);
    
  • API Endpoints: Use Searchable with API resources for filtered responses.

3. Blade Components

  • Pattern: Leverage pre-built components for consistency.
    @laravelBaseAlert('success', 'User created!')
    @laravelBaseButton('Link', route('dashboard'))
    
  • Customization: Override default views by publishing and modifying:
    php artisan vendor:publish --tag="laravel-base-views"
    

4. Security: Cloudflare Turnstile

  • Pattern: Integrate Turnstile for bot protection.
    @laravelBaseTurnstile('site-key')
    
  • Validation:
    use Schaefersoft\LaravelBase\Security\Turnstile;
    
    $valid = Turnstile::verify(request('cf-turnstile-response'), 'secret-key');
    

Integration Tips

  • Service Providers: Register custom form fields or scopes by extending the package's service provider.
  • Configuration: Override defaults in config/laravel-base.php (e.g., form field types, search behavior).
  • Testing: Mock FormGenerator or Searchable traits in unit tests:
    $this->partialMock(FormGenerator::class, 'make');
    

Gotchas and Tips

Pitfalls

  1. FormGenerator Limitations:

    • No CSRF for Non-Blade: Ensure CSRF tokens are manually added for non-Blade forms (e.g., API forms).
    • Field Sanitization: Custom fields may require explicit sanitization to avoid XSS.
    • Asset Dependencies: Forms with JavaScript (e.g., file uploads) need manual asset inclusion.
  2. Searchable Trait:

    • Performance: Complex searches on large datasets may require database indexing or query optimization.
    • Case Sensitivity: Searches are case-sensitive by default; add ->lower() to queries if needed:
      User::search(request()->query())->whereLower('name', 'like', '%john%')->get();
      
    • Reserved Words: Field names like order or group may conflict with SQL keywords; alias them in the $searchable array.
  3. Blade Components:

    • Namespace Conflicts: Avoid naming custom components @laravelBase* to prevent clashes.
    • Asset Loading: Components relying on CSS/JS (e.g., Turnstile) require @vite or @stack directives in layouts.
  4. Turnstile:

    • Rate Limiting: Cloudflare may block excessive verification attempts; implement client-side throttling.
    • Secret Key: Never expose the secret key in client-side code or version control.

Debugging Tips

  • FormGenerator:
    • Use FormGenerator::debug() to inspect generated HTML/attributes.
    • Check for missing enctype="multipart/form-data" in file upload forms.
  • Searchable:
    • Log queries with DB::enableQueryLog() to debug complex searches:
      $query = User::search(['name' => 'John']);
      $query->toSql(); // Inspect SQL
      
  • Blade Components:
    • Clear cached views (php artisan view:clear) after modifying component templates.

Extension Points

  1. Custom Form Fields:

    • Extend Schaefersoft\LaravelBase\Useful\FormGenerator to add fields like:
      public function addCustomField($name, $value = null, $options = [])
      {
          // Logic for custom field (e.g., datepicker, tags)
      }
      
    • Register the field in the service provider:
      FormGenerator::extend('customField', function ($name, $value = null, $options = []) {
          return new CustomField($name, $value, $options);
      });
      
  2. Searchable Extensions:

    • Override the applySearch method in a trait:
      class AdvancedSearchable {
          public function applySearch(Builder $query, array $search)
          {
              // Custom logic (e.g., full-text search, fuzzy matching)
          }
      }
      
    • Use composition:
      class User extends Model
      {
          use Searchable, AdvancedSearchable;
      }
      
  3. Blade Directives:

    • Add custom directives to AppServiceProvider:
      Blade::directive('laravelBaseCustom', function ($expression) {
          return "<?php echo customLogic($expression); ?>";
      });
      

Configuration Quirks

  • Form Defaults: Override config('laravel-base.form.defaults') to change global settings like:
    'defaults' => [
        'method' => 'GET', // Default HTTP method
        'class' => 'form-control', // Default input class
    ],
    
  • Searchable Fields: Use null in $searchable to exclude fields from search:
    protected $searchable = ['name', 'email', null]; // Excludes 'email'
    
  • Turnstile: Configure retry logic for failed verifications in config('laravel-base.turnstile').

Performance

  • Eager Load Searchable Relations: Avoid N+1 queries when searching related models:
    User::with('posts')->search($query)->get();
    
  • Cache Search Results: For static or infrequently changing data:
    $posts = Cache::remember('posts-search', now()->addHours(1), function () {
        return Post::search($query)->get();
    });
    
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.
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
l3aro/rating-star-for-filament
leek/filament-subtenant-scope