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

Rad Bundle Laravel Package

becklyn/rad-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup for Laravel Integration

  1. Install via Composer (Symfony bundle, but core components can be adapted):

    composer require becklyn/rad-bundle
    

    Note: Since this is a Symfony bundle, use only the core classes (AjaxResponseBuilder, SimpleEntitySearchHelper, etc.) via direct dependency injection or facades.

  2. Replicate the AJAX Protocol in Laravel: Create a base controller trait to mirror BaseController::ajaxResponse():

    // app/Traits/AjaxResponseTrait.php
    use Illuminate\Http\JsonResponse;
    
    trait AjaxResponseTrait
    {
        protected function ajaxResponse(
            bool $ok,
            string $status,
            mixed $data = null,
            ?string $redirect = null,
            ?array $message = null
        ): JsonResponse {
            return response()->json([
                'ok' => $ok,
                'status' => $status,
                'data' => $data,
                'redirect' => $redirect,
                'message' => $message,
            ]);
        }
    }
    
  3. First Use Case: AJAX Endpoint Extend a controller to use the trait:

    // app/Http/Controllers/ExampleController.php
    use App\Traits\AjaxResponseTrait;
    
    class ExampleController extends Controller
    {
        use AjaxResponseTrait;
    
        public function fetchData()
        {
            try {
                $data = Model::all();
                return $this->ajaxResponse(true, 'success', $data->toArray());
            } catch (\Exception $e) {
                return $this->ajaxResponse(false, 'error', null, null, [
                    'text' => $e->getMessage(),
                    'impact' => 'negative',
                ]);
            }
        }
    }
    
  4. Frontend Integration: Use the mojave client or adapt the TypeScript interface:

    // types/ajax-response.d.ts
    interface AjaxResponse {
        ok: boolean;
        status: string;
        data: Record<string, any> | any[];
        redirect?: string;
        message?: {
            text: string;
            impact: 'positive' | 'negative' | 'neutral';
            action?: { label: string; url: string };
        };
    }
    

Implementation Patterns

1. AJAX Protocol Workflow

  • Request Handling: Use AjaxResponseTrait in controllers to standardize responses. Example:

    public function create(Request $request)
    {
        $validated = $request->validate([...]);
        $resource = Model::create($validated);
    
        return $this->ajaxResponse(
            true,
            'created',
            $resource,
            route('resource.show', $resource),
            ['text' => 'Resource created successfully', 'impact' => 'positive']
        );
    }
    
  • Error Handling: Catch exceptions and return structured errors:

    catch (ValidationException $e) {
        return $this->ajaxResponse(
            false,
            'validation_error',
            null,
            null,
            ['text' => 'Validation failed', 'impact' => 'negative']
        );
    }
    
  • Redirects: Use the redirect field for SPA-like navigation:

    return $this->ajaxResponse(
        true,
        'redirect_needed',
        null,
        route('dashboard')
    );
    

2. Form Extensions

  • Collection Fields: Adapt Symfony’s CollectionType behavior in Laravel using collective/html or custom views:

    // In a FormRequest or Controller
    public function buildForm(BuilderInterface $builder, array $options)
    {
        $builder->add('tags', CollectionType::class, [
            'entry_type' => TextType::class,
            'allow_add' => true,
            'allow_delete' => true,
            'prototype' => true,
            'entry_options' => [
                'label' => false,
            ],
            'empty_message' => 'No tags added yet',
            'entry_add_label' => 'Add Tag',
            'entry_remove_label' => 'Remove',
        ]);
    }
    

    Note: Laravel lacks native CollectionType, so use packages like laravelcollective/html or build custom logic.

  • JSON Search: Use SimpleEntitySearchHelper for dynamic queries (adapt for Laravel/Eloquent):

    use Becklyn\RadBundle\Helper\SimpleEntitySearchHelper;
    
    class PostRepository
    {
        public function search(array $criteria)
        {
            $query = Post::query();
            $helper = new SimpleEntitySearchHelper();
            $helper->applyJsonSearch($query, $criteria, 'metadata');
            return $query->get();
        }
    }
    

3. Deferred Components

  • Deferred Routes/Translations: Use for lazy-loading routes or translations:

    use Becklyn\RadBundle\Deferred\DeferredRoute;
    
    $route = new DeferredRoute('resource.show', ['id' => $id]);
    if ($route->isValidValue()) {
        $url = $route->generateValue();
    }
    
  • Deferred Forms: For dynamic form generation (Symfony-specific; replicate with Laravel’s FormBuilder or Livewire).

4. Pagination

  • Offset Calculation: Move pagination logic to a helper (mirror Symfony’s Pagination):
    class PaginationHelper
    {
        public static function calculateOffset(int $page, int $perPage): int
        {
            return ($page - 1) * $perPage;
        }
    }
    

Gotchas and Tips

Pitfalls

  1. Symfony Dependencies:

    • Classes like FormBuilder, EventDispatcher, or DependencyInjection won’t work directly in Laravel. Use only the protocol/utility classes (AjaxResponseBuilder, SimpleEntitySearchHelper, etc.).
    • Workaround: Install Symfony components via Composer (e.g., symfony/form) and wrap them in Laravel facades.
  2. TypeScript Interface Mismatch:

    • The AjaxResponse interface assumes specific fields. Deviations (e.g., Laravel’s default JSON structure) will break frontend logic.
    • Fix: Enforce the interface in Laravel responses or adapt mojave to handle both formats.
  3. Form Extensions:

    • Laravel’s Form facade doesn’t support Symfony’s CollectionType out of the box. Custom views or packages like laravelcollective/html are needed.
    • Tip: Use Laravel’s Replicator or DynamicFields packages for similar functionality.
  4. Doctrine vs. Eloquent:

    • SimpleEntitySearchHelper uses Doctrine’s JSON_SEARCH(). For Eloquent, use raw queries or packages like spatie/laravel-query-builder.
  5. Deprecated Features:

    • Avoid BundleExtension (deprecated in v7.13.3). Use standalone classes instead.

Debugging Tips

  1. AJAX Responses:

    • Always check the ok and status fields in frontend logs. Example:
      const response = await fetch('/api/data');
      const data = await response.json();
      if (!data.ok) {
          console.error(`Status: ${data.status}`, data.message);
      }
      
  2. Form Errors:

    • Ensure error messages use the correct translation domain (fixed in v7.12.1). In Laravel, manually set domains:
      trans('validation.custom_field', [], 'messages');
      
  3. JSON Paths:

    • SimpleEntitySearchHelper::applyJsonSearch() requires MySQL’s JSON_SEARCH(). For PostgreSQL, use jsonb_path_query or adapt the helper.

Extension Points

  1. Custom AJAX Protocols:

    • Extend AjaxResponseTrait to add fields (e.g., meta for pagination):
      protected function ajaxResponse(...): JsonResponse
      {
          $response = parent::ajaxResponse(...);
          $response->setData([
              'meta' => ['pagination' => [...]],
              ...$response->getData()
          ]);
          return $response;
      }
      
  2. Frontend Adaptors:

    • Create a Laravel-specific mojave alternative (e.g., laravel-mojave) to handle quirks like CSRF tokens or Laravel’s auth system.
  3. Form Helpers:

    • Build Laravel-specific form extensions (e.g., LaravelCollectionType) that mirror Symfony’s behavior using livewire or inertiajs.

Configuration Quirks

  1. Translation Domains:

    • Form errors default to Symfony’s validators domain. In Laravel, override in config/translation.php:
      'domains' => [
          'validators' => LaravelTranslationDomain::class,
      ],
      
  2. CSRF Protection:

    • The bundle assumes Symfony’s CSRF handling. In Laravel, ensure AJAX requests include _token or use VerifyCsrfToken middleware.
  3. PHP Version:

    • Requires PHP 7.4+. Laravel 8+ (PHP 8.0+) is compatible
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.
bugban/php-sdk
littlerocket/job-queue-bundle
graham-campbell/flysystem
capell-app/block-library
axium/identity
cetria/laravel-dummy-models
cetria/reflection-helper
agropredict/sso-auth-bundle
evolvestudio/spam-protection
directorytree/opensearch-client
directorytree/opensearch-adapter
datacore/hub-sdk
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony
develia/geo-bundle
dreamzy/livewire-charts
touchestate-sdk/php-sdk
22h/doctrine-garbage-collection-bundle
agtp/agtp-php