PHP code example of ritechoice23 / laravel-followable

1. Go to this page and download the library: Download ritechoice23/laravel-followable library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

ritechoice23 / laravel-followable example snippets


return [
    'table_name' => 'follows',
    'allow_self_follow' => false,
    'metadata_column' => 'metadata',
];

use Illuminate\Database\Eloquent\Model;
use Ritechoice23\Followable\Traits\CanFollow;
use Ritechoice23\Followable\Traits\HasFollowers;

class User extends Model
{
    use CanFollow;      // Can follow other models
    use HasFollowers;   // Can be followed by other models
}

class Team extends Model
{
    use HasFollowers;   // Can be followed
}

// Follow a model
$user->follow($team);

// Unfollow a model
$user->unfollow($team);

// Toggle follow status
$user->toggleFollow($team);

// Check if following
if ($user->isFollowing($team)) {
    // User is following the team
}

// Check if followed by
if ($team->isFollowedBy($user)) {
    // Team is followed by user
}

// Get counts
$user->followingCount();  // Number of models user is following
$team->followersCount();  // Number of followers team has

// Get all followers (single type or homogeneous followers)
$followers = $team->followers()->get();

// Paginate followers
$followers = $team->followers()->paginate(15);

// Filter and query like any Eloquent relation
$activeFollowers = $team->followers()
    ->where('is_active', true)
    ->orderBy('name')
    ->get();

// Quick pagination helper
$followers = $team->followersPaginated(10);

// Filter by specific follower type
$userFollowers = $team->followersOfType(User::class)->get();

// ✅ Best approach for mixed types
$grouped = $post->followersGrouped();
// Returns: ['App\Models\User' => Collection<User>, 'App\Models\Team' => Collection<Team>]

// Iterate through each type
foreach ($grouped as $type => $followers) {
    echo "{$type}: {$followers->count()} followers\n";

    foreach ($followers as $follower) {
        // $follower is the actual User or Team model
        echo $follower->name;
    }
}

// Or query specific types separately
$userFollowers = $post->followers(User::class)->get();
$teamFollowers = $post->followers(Team::class)->get();

// Total followers
$totalFollowers = $team->followersCount();

// Count by specific type
$userFollowers = $team->followersCount(User::class);
$teamFollowers = $team->followersCount(Team::class);

// Get Follow pivot records
$followRecords = $team->followRecords;  // Collection<Follow>

// With eager loading
$followRecords = $team->followRecords()->with('follower')->get();

// Access metadata
foreach ($followRecords as $follow) {
    $metadata = $follow->metadata;
    $followerModel = $follow->follower;
}

$user->follow($team, [
    'source' => 'web',
    'campaign' => 'summer_2024',
    'referrer' => 'homepage'
]);

// Access and modify metadata (metadata is cast as array)
$follow = Follow::first();

// Set metadata
$metadata = $follow->metadata ?? [];
$metadata['key'] = 'value';
$follow->metadata = $metadata;
$follow->save();

// Get metadata
$value = $follow->metadata['key'] ?? null;

// Remove metadata key
$metadata = $follow->metadata;
unset($metadata['key']);
$follow->metadata = $metadata;
$follow->save();

// Find all users following a team
$users = User::whereFollowing($team)->get();

// Find all teams followed by a user
$teams = Team::whereFollowers($user)->get();

// Chain with other queries
$activeUsers = User::whereFollowing($team)
    ->where('status', 'active')
    ->orderBy('created_at', 'desc')
    ->get();

$user->follow($organization);  // User → Organization
$user->follow($anotherUser);   // User → User
$team->follow($anotherTeam);   // Team → Team
$user->follow($post);          // User → Post

// Get all follows made by user (Follow records)
$user->followingRecords;

// Get actual follower models
$actualFollowers = $team->followers()->get();

// Get Follow pivot records
$followRecords = $team->followRecords;

// Eager load relationships on Follow records
$follows = Follow::with(['follower', 'followable'])->get();

// Get all followings (single type or homogeneous followings)
$followings = $user->followings()->get();

// Paginate followings
$followings = $user->followings()->paginate(15);

// Filter and query like any Eloquent relation
$activeTeams = $user->followings()
    ->where('is_active', true)
    ->orderBy('name')
    ->get();

// Quick pagination helper
$followings = $user->followingsPaginated(10);

// Filter by specific followable type
$teamFollowings = $user->followingsOfType(Team::class)->get();

// ✅ Best approach for mixed types
$grouped = $user->followingsGrouped();
// Returns: ['App\Models\User' => Collection<User>, 'App\Models\Team' => Collection<Team>]

// Iterate through each type
foreach ($grouped as $type => $followables) {
    echo "{$type}: {$followables->count()} followings\n";

    foreach ($followables as $followable) {
        // $followable is the actual User or Team model
        echo $followable->name;
    }
}

// Or query specific types separately
$userFollowings = $user->followings(User::class)->get();
$teamFollowings = $user->followings(Team::class)->get();

// Total followings
$totalFollowings = $user->followingCount();

// Count by specific type
$userFollowings = $user->followingCount(User::class);
$teamFollowings = $user->followingCount(Team::class);

// Get Follow pivot records
$followingRecords = $user->followingRecords;  // Collection<Follow>

// With eager loading
$followingRecords = $user->followingRecords()->with('followable')->get();

// Access metadata
foreach ($followingRecords as $follow) {
    $metadata = $follow->metadata;
    $followableModel = $follow->followable;
}

// ✅ Recommended: Use followersGrouped()
$grouped = $post->followersGrouped();
foreach ($grouped as $type => $followers) {
    // Each type's followers as proper model instances
}

// ✅ Alternative: Query specific types
$userFollowers = $post->followers(User::class)->get();
$teamFollowers = $post->followers(Team::class)->get();

// ✅ Or: Query and merge manually
$users = $post->followers(User::class)->get();
$teams = $post->followers(Team::class)->get();
$allFollowers = $users->merge($teams);

// config/follow.php
'allow_self_follow' => true,

$user->follow($team);  // true
$user->follow($team);  // false (already following)
bash
php artisan vendor:publish --tag="followable-migrations"
php artisan migrate
bash
php artisan vendor:publish --tag="followable-config"