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

rtconner/laravel-likeable

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require rtconner/laravel-likeable
    php artisan migrate
    
    • The migration creates a likes table with likeable_id, likeable_type, user_id, and created_at columns.
  2. Apply to a Model:

    use Conner\Likeable\Likeable;
    
    class Article extends Model
    {
        use Likeable;
    }
    
  3. First Use Case:

    $article = Article::find(1);
    $article->like(); // Likes for authenticated user
    $article->likeCount; // Returns integer count
    

Key Initial Actions

  • Run php artisan migrate to set up the database table.
  • Use use Likeable; in any Eloquent model needing like functionality.
  • Test core methods (like(), unlike(), liked()) in Tinker or a controller.

Implementation Patterns

Core Workflows

  1. Basic Like/Unlike:

    // Authenticated user
    $post->like(); // Adds like record
    $post->unlike(); // Removes like record
    
    // Anonymous or custom user
    $post->like($userId); // Explicit user ID
    $post->unlike($userId);
    
  2. Counting and Checking:

    $post->likeCount; // Integer count
    $post->liked(); // Boolean: true if current user liked
    $post->liked($userId); // Check for specific user
    
  3. Query Scopes:

    // Get posts liked by user
    $userLikedPosts = Post::whereLikedBy(auth()->id())->get();
    
    // Get posts with >10 likes
    $popularPosts = Post::where('like_count', '>', 10)->get();
    

Integration Tips

  • Authentication: Use auth()->id() for seamless integration with Laravel’s auth system.
  • APIs: Pass user IDs explicitly for stateless APIs:
    $post->like($request->user_id);
    
  • Real-time Updates: Pair with Laravel Echo/Pusher to update like counts dynamically.
  • Caching: Cache likeCount in Redis for high-traffic models:
    Cache::remember("post:{$post->id}:likes", now()->addHours(1), fn() => $post->likeCount);
    

Advanced Patterns

  1. Polymorphic Likes:

    // Works out-of-the-box for any model using the trait
    $comment->like(); // Uses same table as Article
    
  2. Batch Operations:

    // Unlike all posts by a user
    Post::where('user_id', $userId)->get()->each->unlike($userId);
    
  3. Customizing the Likeable Table: Override getLikeableTable() in your model:

    public function getLikeableTable()
    {
        return 'custom_likes';
    }
    

Gotchas and Tips

Common Pitfalls

  1. Migration Errors:

    • Ensure the likes table exists. Run php artisan migrate if skipped.
    • If using custom tables, manually create the table before applying the trait.
  2. User ID Handling:

    • Passing 0 as $userId increments/decrements the count without tracking a user. Use sparingly.
    • unlike(0) removes all likes (resets count to 0). Confirm intent before use.
  3. Polymorphic Conflicts:

    • Avoid naming conflicts with likeable_type (e.g., don’t use type as a model column).
    • Debug with:
      $post->getLikeableTable(); // Verify table name
      $post->getLikeableKey();   // Verify key column (default: 'id')
      
  4. Performance:

    • likes collection loads all like records. Use likeCount for counts or limit with:
      $post->likes()->limit(5)->get();
      

Debugging Tips

  1. Check Like Records:

    $post->likes; // Inspect raw records
    $post->likes()->where('user_id', $userId)->exists(); // Verify existence
    
  2. Log Queries: Enable Laravel’s query logging in config/database.php:

    'log' => env('DB_LOG_QUERIES', false),
    

    Then check storage/logs/laravel.log.

  3. Override Methods: Extend the trait for custom logic:

    class Article extends Model
    {
        use Likeable;
    
        public function like($userId = null)
        {
            if ($this->isPremiumUser()) {
                // Custom logic
            }
            parent::like($userId);
        }
    }
    

Extension Points

  1. Custom Columns: Override getLikeableKey() or getLikeableForeignKey():

    public function getLikeableKey()
    {
        return 'slug'; // Use slug instead of ID
    }
    
  2. Event Hooks: Listen for like/unlike events:

    Likeable::like(function ($model, $userId) {
        event(new PostLiked($model, $userId));
    });
    
  3. Validation: Add middleware to validate user actions:

    public function unlike($userId = null)
    {
        if ($this->isBanned()) {
            abort(403);
        }
        parent::unlike($userId);
    }
    

Configuration Quirks

  • Default User ID: The trait uses auth()->id() by default. For APIs, override or pass IDs explicitly.
  • Soft Deletes: If your model uses soft deletes, ensure the likes table also has a deleted_at column and update the trait’s queries accordingly.
  • Timestamps: The likes table includes created_at but not updated_at. Add if needed:
    public function getLikeableCreatedAtColumn()
    {
        return 'created_at';
    }
    
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.
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
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