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

miladimos/laravel-social

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation:

    composer require miladimos/laravel-social
    php artisan social:install
    php artisan migrate
    

    Add Miladimos\Social\Providers\SocialServiceProvider::class to config/app.php under providers.

  2. Enable Follow/Unfollow:

    • Add Followable trait to your User model:
      use Miladimos\Social\Traits\Follows\Followable;
      
    • Publish config (if needed) with:
      php artisan vendor:publish --provider="Miladimos\Social\Providers\SocialServiceProvider"
      
  3. First Use Case:

    use App\Models\User;
    
    $user = User::find(1);
    $targetUser = User::find(2);
    
    // Follow
    $user->follow($targetUser);
    
    // Unfollow
    $user->unfollow($targetUser);
    
    // Toggle (follow/unfollow)
    $user->toggleFollow($targetUser);
    

Where to Look First

  • Config: config/socials.php (for customizing follow/unfollow behavior).
  • Traits: Followable trait in Traits/Follows/Followable.php (core logic).
  • Migrations: database/migrations/[timestamp]_create_follows_table.php (schema for relationships).

Implementation Patterns

Core Workflows

  1. Basic Follow/Unfollow:

    // Follow a user
    $user->follow($targetUser);
    
    // Check if followed
    $user->isFollowing($targetUser); // Returns boolean
    
    // Get followers/following
    $user->followers(); // Collection of followers
    $user->following(); // Collection of followed users
    
  2. Batch Operations:

    // Follow multiple users
    $user->follow([$user1, $user2, $user3]);
    
    // Unfollow multiple users
    $user->unfollow([$user1, $user2]);
    
  3. Event Listeners: The package fires events (e.g., Followed, Unfollowed). Listen via:

    use Miladimos\Social\Events\Followed;
    
    event(new Followed($user, $targetUser));
    

    Or register in EventServiceProvider:

    protected $listen = [
        Followed::class => [
            'App\Listeners\LogFollowActivity',
        ],
    ];
    
  4. API Integration: Useful for RESTful endpoints:

    // Follow endpoint
    public function follow(User $user, User $targetUser) {
        $user->follow($targetUser);
        return response()->json(['message' => 'Followed successfully']);
    }
    

Integration Tips

  • Middleware: Protect follow/unfollow routes with auth middleware:
    Route::middleware(['auth'])->group(function () {
        Route::post('/follow/{user}', [FollowController::class, 'follow']);
    });
    
  • Notifications: Trigger notifications on follow/unfollow:
    $user->follow($targetUser);
    Notification::send($targetUser, new UserFollowedNotification($user));
    
  • Eager Loading: Optimize queries when fetching users with relationships:
    $user = User::with(['followers', 'following'])->find(1);
    

Gotchas and Tips

Pitfalls

  1. Missing Trait: Forgetting to add Followable to the User model will cause MethodNotFoundException. Fix: Ensure the trait is included in the model.

  2. Circular Follows: The package does not prevent circular follows (A follows B, B follows A). Handle this in business logic if needed.

  3. Database Constraints: The follows table uses user_id and followed_user_id with unique constraint. Attempting to follow the same user twice will fail silently (no error, but no duplicate entry). Debug: Check for silent failures by logging:

    try {
        $user->follow($targetUser);
    } catch (\Exception $e) {
        Log::error("Follow failed: " . $e->getMessage());
    }
    
  4. Model Caching: If using model caching (e.g., remember()), ensure relationships are refreshed after follow/unfollow:

    $user->follow($targetUser);
    $user->refresh(); // Force reload relationships
    

Debugging Tips

  • Query Logging: Enable Laravel's query logging to inspect generated SQL:
    DB::enableQueryLog();
    $user->follow($targetUser);
    dd(DB::getQueryLog());
    
  • Event Debugging: Listen for events in Tinker to verify triggers:
    php artisan tinker
    >>> event(new \Miladimos\Social\Events\Followed($user, $targetUser));
    

Extension Points

  1. Custom Follow Logic: Override the follow method in your User model:

    public function follow(User $user, $silent = false) {
        // Custom logic (e.g., validate before following)
        if ($user->isBlocked()) {
            throw new \Exception("Cannot follow blocked user");
        }
        $this->followableFollow($user, $silent);
    }
    
  2. Additional Relationships: Extend the package to support "mutual follows" or "blocking":

    // Add to Followable trait or create a new trait
    public function isMutualFollow(User $user) {
        return $this->following()->contains($user) && $user->following()->contains($this);
    }
    
  3. Custom Events: Extend the default events or create new ones:

    class CustomFollowEvent extends Event {
        public $user;
        public $targetUser;
        public $metadata;
    
        public function __construct(User $user, User $targetUser, array $metadata) {
            $this->user = $user;
            $this->targetUser = $targetUser;
            $this->metadata = $metadata;
        }
    }
    
  4. API Resources: Create custom API resources for followers/following:

    public function toArray($request) {
        return [
            'id' => $this->id,
            'name' => $this->name,
            'is_following' => auth()->user()->isFollowing($this),
        ];
    }
    

Config Quirks

  • Default Guard: The package assumes the default auth guard. Override in config/socials.php:
    'guard' => 'admin', // Custom guard name
    
  • Soft Deletes: If your User model uses soft deletes, ensure the follows table handles them:
    // In Followable trait, modify queries to include `withTrashed()` if needed.
    
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