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

becklyn/rad

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation Add the package via Composer:

    composer require becklyn/rad
    

    Enable the bundle in config/bundles.php (Symfony) or register the service provider in config/app.php (Laravel via Symfony bridge):

    Becklyn\RadBundle\RadBundle::class => ['all' => true],
    
  2. First Use Case Use the AjaxResponseBuilder to return standardized AJAX responses. Example in a Symfony controller:

    use Becklyn\RadBundle\AjaxResponseBuilder;
    
    public function someAction(Request $request, AjaxResponseBuilder $builder)
    {
        try {
            // Business logic here
            return $builder->success('ok', ['data' => 'your_data']);
        } catch (\Exception $e) {
            return $builder->error('invalid-id', [], $e->getMessage());
        }
    }
    
  3. Frontend Integration Use the mojave library (TypeScript) to handle responses. Example:

    const response = await fetch('/some-endpoint', { method: 'POST' });
    const data = await response.json();
    if (!data.ok) {
        // Handle error (e.g., show toast)
        mojave.toast(data.message);
    }
    

Implementation Patterns

Standardized AJAX Responses

  • Consistent Structure: Always return responses matching the AjaxResponse interface. Use AjaxResponseBuilder for boilerplate:

    // Success with redirect
    $builder->success('user_created', ['id' => 123], '/dashboard');
    
    // Error with toast
    $builder->error('validation_failed', [], 'Invalid input', 'negative');
    
  • Workflow Integration:

    1. Controller Layer: Use AjaxResponseBuilder for all AJAX endpoints.
    2. Service Layer: Pass the builder to services handling business logic.
    3. Frontend: Decouple logic from UI using mojave to handle ok/status/data triad.

Error Handling

  • Avoid 400 Errors: The bundle defaults to HTTP 200 for all AJAX responses, even errors. Use status field for granular error handling:
    return $builder->error('not_found', [], 'Resource not found');
    
    Frontend checks data.ok and data.status to route errors.

Toast Messages

  • Dynamic Feedback: Leverage the message field for user feedback:
    return $builder->success('updated', [], null, [
        'text' => 'Profile saved!',
        'impact' => 'positive',
        'action' => ['label' => 'View', 'url' => '/profile']
    ]);
    
    Render in frontend with:
    mojave.toast(data.message);
    

Redirects

  • AJAX Redirects: Use the redirect field to trigger client-side navigation:
    return $builder->success('created', [], '/dashboard');
    
    Handle in frontend:
    if (data.redirect) window.location.href = data.redirect;
    

Gotchas and Tips

Pitfalls

  1. Symfony-Centric Design:

    • The package is built for Symfony. In Laravel, use a Symfony bridge (e.g., symfony/http-foundation) or adapt controllers to return JSON manually.
    • Example Laravel workaround:
      return response()->json([
          'ok' => true,
          'status' => 'success',
          'data' => $data,
      ]);
      
  2. TypeScript Dependency:

    • The AjaxResponse interface assumes TypeScript (mojave). For vanilla JS, manually type-check responses:
      if (!response.ok || !response.data) throw new Error('Invalid response');
      
  3. HTTP Status Codes:

    • The bundle ignores HTTP status codes (always 200). Override in Laravel by returning Response objects directly:
      return response()->json([...], 404);
      

Debugging

  • Response Validation: Ensure all responses include ok, status, and data. Use a middleware to validate:

    public function handle(Request $request, Closure $next)
    {
        $response = $next($request);
        if ($response->isJson()) {
            $data = json_decode($response->getContent(), true);
            if (!isset($data['ok'], $data['status'], $data['data'])) {
                throw new \RuntimeException('Invalid AJAX response format');
            }
        }
        return $response;
    }
    
  • Frontend Debugging: Log raw responses to verify structure:

    console.log('AJAX Response:', data);
    

Extension Points

  1. Custom Response Builders: Extend AjaxResponseBuilder to add project-specific fields:

    class CustomResponseBuilder extends AjaxResponseBuilder
    {
        public function withMeta(array $meta): self
        {
            $this->data['meta'] = $meta;
            return $this;
        }
    }
    
  2. Override Default Protocol: Replace AjaxResponseBuilder with a custom implementation if the interface doesn’t fit your needs.

  3. Laravel Integration: For Laravel, create a facade or helper to wrap the Symfony builder:

    // app/Helpers/AjaxHelper.php
    use Becklyn\RadBundle\AjaxResponseBuilder;
    
    class AjaxHelper
    {
        public static function success(string $status, array $data, ?string $redirect = null): array
        {
            return (new AjaxResponseBuilder())->success($status, $data, $redirect)->toArray();
        }
    }
    

Configuration Quirks

  • No Config File: The bundle has no configuration options. All behavior is code-driven via AjaxResponseBuilder.
  • Namespace Collisions: Ensure Becklyn\RadBundle doesn’t conflict with other Rad-named packages. Use fully qualified namespaces.
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.
comsave/common
alecsammon/php-raml-parser
chrome-php/wrench
lendable/composer-license-checker
typhoon/reflection
mesilov/moneyphp-percentage
mike42/gfx-php
bookdown/themes
aura/view
aura/html
aura/cli
povils/phpmnd
nayjest/manipulator
omnipay/tests
psr-mock/http-message-implementation
psr-mock/http-factory-implementation
psr-mock/http-client-implementation
voku/email-check
voku/urlify
rtheunissen/guzzle-log-middleware