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

Products Favorite Laravel Package

baks-dev/products-favorite

Laravel/PHP module for managing product favorites (wishlist): add/remove products to a user’s favorites, store and retrieve favorite lists, and integrate into e-commerce product pages. Requires PHP 8.4+.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation:

    composer require baks-dev/products-favorite
    

    Add the service provider to config/app.php:

    BaksDev\ProductsFavorite\ProductsFavoriteServiceProvider::class,
    
  2. Publish Config/Views (if needed):

    php artisan vendor:publish --tag=products-favorite-config
    php artisan vendor:publish --tag=products-favorite-views
    
  3. Run Migrations (if new tables are introduced):

    php artisan migrate
    
  4. First Use Case: Toggle a product favorite for the authenticated user:

    use BaksDev\ProductsFavorite\Facades\Favorite;
    
    // Add to favorites
    Favorite::toggle($productId);
    
    // Check if product is favorited
    $isFavorited = Favorite::isFavorited($productId);
    

Where to Look First

  • Facade: app/Facades/Favorite.php for core methods (toggle(), isFavorited()).
  • Service Provider: src/ProductsFavoriteServiceProvider.php for bindings and events.
  • Models: src/Models/Favorite.php for relationships and business logic.
  • Migrations: database/migrations/ for schema changes (if any).
  • Tests: tests/Feature/ProductsFavoriteTest.php for usage examples.

Implementation Patterns

Core Workflows

  1. Basic CRUD:

    // Add/remove a product from favorites
    Favorite::toggle($productId);
    
    // List all user favorites
    $favorites = Favorite::forUser()->get();
    
    // Check if a product is favorited
    if (Favorite::isFavorited($productId)) { ... }
    
  2. Event-Driven Extensions: Listen for favorite events to trigger side effects (e.g., notifications):

    // In EventServiceProvider
    protected $listen = [
        \BaksDev\ProductsFavorite\Events\FavoriteAdded::class => [
            \App\Listeners\SendFavoriteNotification::class,
        ],
    ];
    
  3. API Integration: Use Laravel’s built-in API resources or create custom endpoints:

    Route::post('/favorites/{product}', [FavoriteController::class, 'toggle']);
    
  4. Frontend Integration:

    • Blade: Use published views (if available) or create custom templates.
    • Livewire/Inertia: Call facade methods directly in components.
    • JavaScript: Fetch favorited status via API:
      axios.get(`/api/favorites/${productId}`).then(response => {
          const isFavorited = response.data.is_favorited;
      });
      

Integration Tips

  • Authentication: Ensure Auth::user() is bound in middleware (e.g., auth:api).
  • Model Binding: Extend the Favorite model if your Product or User models differ:
    use BaksDev\ProductsFavorite\Models\Favorite as BaseFavorite;
    
    class Favorite extends BaseFavorite {
        public function product() {
            return $this->belongsTo(Product::class, 'product_id');
        }
    }
    
  • Caching: Cache favorited status for performance:
    Cache::remember("user_{$userId}_favorites", now()->addHours(1), function () use ($userId) {
        return Favorite::forUser($userId)->pluck('product_id');
    });
    
  • Validation: Override validation rules in app/Providers/AppServiceProvider.php:
    Favorite::extend(function ($favorite) {
        $favorite->validate(function ($data) {
            return Validator::make($data, [
                'product_id' => 'required|exists:products,id',
            ]);
        });
    });
    

Gotchas and Tips

Pitfalls

  1. Model Assumptions:

    • The package assumes User and Product models exist with id fields. Customize if your schema differs.
    • Fix: Extend the Favorite model to match your relationships.
  2. Authentication Bypass:

    • Unauthenticated users may trigger favorite logic if not guarded.
    • Fix: Use middleware:
      Route::middleware('auth')->post('/favorites/{product}', ...);
      
  3. Duplicate Favorites:

    • No built-in deduplication for rapid toggles (e.g., double-clicks).
    • Fix: Add a unique index or handle in the toggle() method:
      Favorite::firstOrCreate([
          'user_id' => auth()->id(),
          'product_id' => $productId,
      ]);
      
  4. Missing Events:

    • Events like FavoriteRemoved may not be published by default.
    • Fix: Manually dispatch in the toggle() method or extend the service.
  5. Database Locking:

    • High-traffic sites may experience race conditions on toggle().
    • Fix: Use database transactions or optimistic locking:
      DB::transaction(function () use ($productId) {
          Favorite::toggle($productId);
      });
      

Debugging Tips

  • Check Events: Verify events are fired with:
    php artisan event:listen BaksDev\ProductsFavorite\Events\FavoriteAdded
    
  • Log Facade Calls: Temporarily add logging to the facade:
    \Log::debug('Favorite toggle called for product', ['product_id' => $productId]);
    
  • Test Migrations: Use --pretend to preview schema changes:
    php artisan migrate --pretend
    
  • Inspect Middleware: Ensure auth middleware is applied to routes:
    php artisan route:list | grep favorites
    

Extension Points

  1. Custom Validation:

    Favorite::extend(function ($favorite) {
        $favorite->validate(function ($data) {
            return Validator::make($data, [
                'product_id' => 'required|exists:products,id|not_in:blacklisted_products',
            ]);
        });
    });
    
  2. Add Metadata: Extend the Favorite model to store additional fields (e.g., created_at notes):

    Schema::table('favorites', function (Blueprint $table) {
        $table->text('notes')->nullable();
    });
    
  3. API Resources: Create a custom resource for API responses:

    namespace App\Http\Resources;
    
    use Illuminate\Http\Resources\Json\JsonResource;
    
    class FavoriteResource extends JsonResource {
        public function toArray($request) {
            return [
                'product_id' => $this->product_id,
                'created_at' => $this->created_at->format('Y-m-d'),
                'notes' => $this->notes,
            ];
        }
    }
    
  4. Real-Time Updates: Use Laravel Echo/Pusher to broadcast favorite changes:

    broadcast(new FavoriteUpdated($productId, $isFavorited));
    
  5. Bulk Operations: Add methods to the facade for batch processing:

    Favorite::extend(function ($favorite) {
        $favorite->bulkToggle(array $productIds) {
            // Implement logic
        }
    });
    

Configuration Quirks

  • No Default Config: The package may not publish a config file by default. Check for:
    php artisan vendor:publish --tag=products-favorite-config
    
  • Locale Support: If using translations, ensure the package’s language files are published:
    php artisan vendor:publish --tag=products-favorite-lang
    
  • Queue Workers: If using queued events, ensure your queue worker is running:
    php artisan queue:work
    
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.
codifyo/ts-generator-bundle
andydefer/laravel-cluster
testo/fiber
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