This package helps you to add user based follow system to your model.

Overview

Laravel Follow

User follow unfollow system for Laravel.

Latest Stable Version Latest Unstable Version Build Status Scrutinizer Code Quality Total Downloads License

Related projects:

Sponsor me

Installing

$ composer require overtrue/laravel-follow -vvv

Configuration

This step is optional

$ php artisan vendor:publish --provider="Overtrue\\LaravelFollow\\FollowServiceProvider" --tag=config

Migrations

This step is also optional, if you want to custom the pivot table, you can publish the migration files:

$ php artisan vendor:publish --provider="Overtrue\\LaravelFollow\\FollowServiceProvider" --tag=migrations

Usage

Traits

Overtrue\LaravelFollow\Followable

use Illuminate\Notifications\Notifiable;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Overtrue\LaravelFollow\Followable;

class User extends Authenticatable
{
    <...>
    use Followable;
    <...>
}

API

$user1 = User::find(1);
$user2 = User::find(2);

$user1->follow($user2);
$user1->unfollow($user2);
$user1->toggleFollow($user2);
$user1->acceptFollowRequestFrom($user2);
$user1->rejectFollowRequestFrom($user2);

$user1->isFollowing($user2);
$user2->isFollowedBy($user1);
$user2->hasRequestedToFollow($user1);

$user1->areFollowingEachOther($user2);

Get followings:

$user->followings;

Get followers:

$user->followers;

Follow Requests

If you would like to have some follow requests to need to be accepted by the user being followed, simply override the needsToApproveFollowRequests() method in the model that uses the Followable trait with your custom logic:

public function needsToApproveFollowRequests()
{
    // Your custom logic here
    return (bool) $this->private;
}

Aggregations

// followings count
$user->followings()->count();

// with query where
$user->followings()->where('gender', 'female')->count();

// followers count
$user->followers()->count();

List with *_count attribute:

$users = User::withCount(['followings', 'followers'])->get();

foreach($users as $user) {
    // $user->followings_count;
    // $user->followers_count;
}

Attach user follow status to followable collection

You can use Followable::attachFollowStatus(Collection $followables) to attach the user favorite status, it will set has_followed attribute to each model of $followables:

For model

1 "name" => "user1" "private" => false "created_at" => "2021-06-07T15:06:47.000000Z" "updated_at" => "2021-06-07T15:06:47.000000Z" "has_followed" => true ] ">
$user1 = User::find(1);

$user->attachFollowStatus($user1);

// result
[
    "id" => 1
    "name" => "user1"
    "private" => false
    "created_at" => "2021-06-07T15:06:47.000000Z"
    "updated_at" => "2021-06-07T15:06:47.000000Z"
    "has_followed" => true  
  ]

For Collection | Paginator | LengthAwarePaginator | array:

1 "name" => "user1" "private" => false "created_at" => "2021-06-07T15:06:47.000000Z" "updated_at" => "2021-06-07T15:06:47.000000Z" "has_followed" => true ], [ "id" => 2 "name" => "user2" "private" => false "created_at" => "2021-06-07T15:06:47.000000Z" "updated_at" => "2021-06-07T15:06:47.000000Z" "has_followed" => true ], [ "id" => 3 "name" => "user3" "private" => false "created_at" => "2021-06-07T15:06:47.000000Z" "updated_at" => "2021-06-07T15:06:47.000000Z" "has_followed" => false ], [ "id" => 4 "name" => "user4" "private" => false "created_at" => "2021-06-07T15:06:47.000000Z" "updated_at" => "2021-06-07T15:06:47.000000Z" "has_followed" => false ], ] ">
$user = auth()->user();

$users = User::oldest('id')->get();

$users = $user->attachFollowStatus($users);

$users = $users->toArray();

// result
[
  [
    "id" => 1
    "name" => "user1"
    "private" => false
    "created_at" => "2021-06-07T15:06:47.000000Z"
    "updated_at" => "2021-06-07T15:06:47.000000Z"
    "has_followed" => true  
  ],
  [
    "id" => 2
    "name" => "user2"
    "private" => false
    "created_at" => "2021-06-07T15:06:47.000000Z"
    "updated_at" => "2021-06-07T15:06:47.000000Z"
    "has_followed" => true
  ],
  [
    "id" => 3
    "name" => "user3"
    "private" => false
    "created_at" => "2021-06-07T15:06:47.000000Z"
    "updated_at" => "2021-06-07T15:06:47.000000Z"
    "has_followed" => false
  ],
  [
    "id" => 4
    "name" => "user4"
    "private" => false
    "created_at" => "2021-06-07T15:06:47.000000Z"
    "updated_at" => "2021-06-07T15:06:47.000000Z"
    "has_followed" => false
  ],
]

For pagination

$users = User::paginate(20);

$user->attachFollowStatus($users);

Order by followers count

You can query users order by followers count with following methods:

  • orderByFollowersCountDesc()
  • orderByFollowersCountAsc()
  • orderByFollowersCount(string $direction = 'desc')

example:

$users = User::orderByFollowersCountDesc()->get();
$mostPopularUser = User::orderByFollowersCountDesc()->first();

N+1 issue

To avoid the N+1 issue, you can use eager loading to reduce this operation to just 2 queries. When querying, you may specify which relationships should be eager loaded using the with method:

$users = User::with('followings')->get();

foreach($users as $user) {
    $user->isFollowing(2);
}

$users = User::with('followers')->get();

foreach($users as $user) {
    $user->isFollowedBy(2);
}

Events

Event Description
Overtrue\LaravelFollow\Events\Followed Triggered when the relationship is created.
Overtrue\LaravelFollow\Events\Unfollowed Triggered when the relationship is deleted.

❤️ Sponsor me

Sponsor me

如果你喜欢我的项目并想支持它,点击这里 ❤️

Project supported by JetBrains

Many thanks to Jetbrains for kindly providing a license for me to work on this and other open-source projects.

Contributing

You can contribute in one of three ways:

  1. File bug reports using the issue tracker.
  2. Answer questions or fix bugs on the issue tracker.
  3. Contribute new features or update the wiki.

The code contribution process is not very formal. You just need to make sure that you follow the PSR-0, PSR-1, and PSR-2 coding guidelines. Any new code contributions must be accompanied by unit tests where applicable.

PHP 扩展包开发

想知道如何从零开始构建 PHP 扩展包?

请关注我的实战课程,我会在此课程中分享一些扩展开发经验 —— 《PHP 扩展包实战教程 - 从入门到发布》

License

MIT

Comments
  • Trait 'Illuminate\Foundation\Events\Dispatchable' not found

    Trait 'Illuminate\Foundation\Events\Dispatchable' not found

    hello guys...

    i added this package to my laravel projects but after use follow() function return this error :

    Trait 'Illuminate\Foundation\Events\Dispatchable' not found in ROOT/vendor/overtrue/laravel-follow/src/Events/Event.php on line 27

    in User App Model i'm using : use CanFollow, CanBeFollowed;

    please help me ;-(

    opened by t0x1c0d3r 29
  • 1.1.8 Issue

    1.1.8 Issue

    Since moving from 1.1.7 to 1.1.8 I now get

    Incorrect syntax near the keyword 'IS'. (SQL: select [users].*, pivot_followables.user_id IS NOT NULL AS pivot_each_other, [followables].[followable_id] as [pivot_followable_id], [followables].[user_id] as [pivot_user_id], [followables].[followable_type] as [pivot_followable_type], [followables].[relation] as [pivot_relation], [followables].[created_at] as [pivot_created_at] from [users] inner join [followables] on [users].[id] = [followables].[user_id] left join [followables] as [pivot_followables] on [pivot_followables].[followable_type] = 'App\Suggestion' and [pivot_followables].[followable_id] = [followables].[user_id] and [pivot_followables].[user_id] = [followables].[followable_id] where [followables].[followable_id] = 1066 and [followables].[followable_type] = App\Suggestion and [followables].[relation] = follow

    when going $object->followers()->get()

    opened by snazy2000 21
  • Nothing added to database

    Nothing added to database

    I have tried the following but it doesn't work

    ` public function followProfessional($slug) { $professional = Professional::where('slug', $slug)->first(); if(! $professional) {

         return redirect()->back()->with('error', 'Professional does not exist.');
       }
    
      $user = Auth::user()->id;
      $user->follow($professional);
      return redirect()->back()->with('success', 'You are currently following this professional.');
    }
    

    `

    And in my view

    <a href="{{ url('professionals/'.$professional->category->slug.'/'.$professional->slug.'/follow') }}" class="btn btn-sm white">Follow</a>

    And in my route Route::get('professionals/{professionalcategory}/{slug}/follow', 'ProfessionalController@followProfessional')->name('professional.follow');

    When i click on the follow button the page just refreshes back but doesn't add anything to the followables table

    Could anyone help me out in this?

    opened by ghost 20
  • Not able to use hasLiked

    Not able to use hasLiked

    Auth::user() with id:1 have liked a post with id:119

    capture

    But when I try this: {{ dd (Auth::user()->hasLiked(119)) }} OR {{ dd (Auth::user()->hasLiked($post->id)) }} It return false

    opened by a-ssassi-n 13
  • get General error: 1 no such table: followables error

    get General error: 1 no such table: followables error

    i want use this package but when i run $user1->follow($user2); i get Illuminate\Database\QueryException with message 'SQLSTATE[HY000]: General error: 1 no such table: followables (SQL: select * from "followables" where "followables"."user_id" = 1 and "followables"."user_id" is not null and ("followable_id" = 2 and "followable_type" = App\Models\User) limit 1)'

    error

    opened by 0xezady 12
  • Question: How to send notification/email to user when they have a new follower?

    Question: How to send notification/email to user when they have a new follower?

    Hello, Thanks for the great package. I just started using it on Laravel 8. I know there is an even triggered when a follow happens, but can someone please point me how to use this to send a notification or email to the user telling them "you have a new follower: <name_of_follower>" kind of message.

    Thanks again for any help. PS: I am just an 57 yr old guy just starting with Laravel (not even a developer, but an enthusiast. Help is highly appreciated)

    opened by samialtaher 11
  • Making follows polymorphic

    Making follows polymorphic

    I am not sure what your roadmap includes for this but I was wondering if there was any thoughts to making it polymorphic in the near future. Follow is one of those things that can be related to multiple models not just users. I would be interested in helping you accomplish this sooner than later with a donation if that would help

    opened by ams-ryanolson 11
  • n+1 problem

    n+1 problem

    I am loading a list of items that has the CanBeFavorited trait. I am also loading the authed users favorites with auth()->user()->load('favorites'). However, the hasFavorited($item) is not using the already loaded relationship, but instead it is querying the database creating an n+1 problem.

    A possible solution would be to check in the hasFavorited if the relation is already loaded, using relationLoaded('favorites'), then use that.

    enhancement help wanted 
    opened by Livijn 10
  • Trait 'Overtrue\LaravelFollow\Traits\CanFollow' not found

    Trait 'Overtrue\LaravelFollow\Traits\CanFollow' not found

    After php artisan vendor:publish I migrated the tables. My User Model looks like this:

    <?php
    namespace App;
    use Illuminate\Foundation\Auth\User as Authenticatable;
    use Overtrue\LaravelFollow\Traits\CanBeFollowed;
    use Overtrue\LaravelFollow\Traits\CanFollow;
    class User extends Authenticatable
    {
        use CanFollow, CanBeFollowed;
    ....
    }
    

    But I am getting

    FatalErrorException in User.php line 11:
    Trait 'Overtrue\LaravelFollow\Traits\CanFollow' not found
    
    opened by a-ssassi-n 10
  • Error Traits

    Error Traits

    Symfony \ Component \ ErrorHandler \ Error \ FatalError

    App\Models\User cannot use Overtrue\LaravelFollow\Followable - it is not a trait

    namespace App\Models;

    use Illuminate\Contracts\Auth\MustVerifyEmail;

    use Illuminate\Database\Eloquent\Factories\HasFactory;

    use Illuminate\Foundation\Auth\User as Authenticatable;

    use Illuminate\Notifications\Notifiable;

    use Laravel\Fortify\TwoFactorAuthenticatable;

    use Laravel\Jetstream\HasProfilePhoto;

    use Laravel\Jetstream\HasTeams;

    use Laravel\Sanctum\HasApiTokens;

    use Overtrue\LaravelFollow\Followable;

    class User extends Authenticatable

    {

    use HasApiTokens;
    
    use HasFactory;
    
    use HasProfilePhoto;
    
    use HasTeams;
    
    use Notifiable;
    
    use TwoFactorAuthenticatable;
    
    use Followable;
    
    opened by Bolibick 9
  • How to count relation?

    How to count relation?

    Hi,

    I have a model App\User which is imported CanLike trait, and 2 models App\Post, App\Video which are imported CanBeLiked. Now I need to count how many likes an user has performed on these models (Post & Video).

    As usual, I have used withCount() method like this:

    $user = User::withCount(['likes'])->get();

    or

    $user->likes()->count();

    But the results of above code always were 0 all of the times. However, with likes method, it worked fine if I passed a param for it:

    $user->likes(\App\Post:class)->count();

    So, what I want to ask here is how can I count how many likes an user has performed on all CanBeLiked model with Laravel's withCount() method. All help is appreciated!

    Thanks,

    bug 
    opened by r94ever 9
  • how to recover data from the

    how to recover data from the "following" user?

    how to recover data from the "following" user?

    I'm trying to retrieve the "following" date but I can't, how can I retrieve, for example, the name of the "followings"? Thanks in advance. My HomeController -->

    ` public function userFollow($username) { $user = User::where('username', $username)->firstOrFail();

        $posts = Post::where('user_id', $user->id)->simplePaginate(3);
        $user = User::find($user->id);
        $followings = User::with('followings')->get();
    
        return view('/@')->with(['user' => $user, 'posts' => $posts, 'followings' => $followings]);
    
    }`
    

    @foreach($followings as $following)

    {{$following->username}} --> problem returns all users in system :(

    @endforeach

    opened by applive3 2
  • $user->followings not working properly

    $user->followings not working properly

    $user->followings
    give me this : { "id": 4, "user_id": 4, "followable_type": "App\Models\User", "followable_id": 3, "accepted_at": "2022-12-15T00:40:51.000000Z", "created_at": "2022-12-15T00:40:51.000000Z", "updated_at": "2022-12-15T00:40:51.000000Z" }

    not user object like the followers ... any help ?!

    thanks

    opened by IslamHeza 6
Releases(5.0.1)
  • 5.0.1(Jun 25, 2022)

    What's Changed

    • fix get config from the right file by @ahmedesa in https://github.com/overtrue/laravel-follow/pull/175

    New Contributors

    • @ahmedesa made their first contribution in https://github.com/overtrue/laravel-follow/pull/175

    Full Changelog: https://github.com/overtrue/laravel-follow/compare/5.0.0...5.0.1

    Source code(tar.gz)
    Source code(zip)
  • 5.0.0(May 18, 2022)

    Now you can follow any models. #170

    What’s Changed

    • Default table name user_followers changed to followables.
    • Renamed followers.follower_id to user_id(you can change it in the config file app/follow.php).
    • Renamed trait Overtrue\LaravelFollow\Followable to use Overtrue\LaravelFollow\Traits\Followable.
    • follow(), unfollow() and toggleFollow() only accept model used Overtrue\LaravelFollow\Traits\Followable trait now.
    • Removed Followable::areFollowingEachOther method.
    • rejectFollowRequestFrom(), acceptFollowRequestFrow(), hasRequestedToFollow() and isFollowedBy only accept model used Overtrue\LaravelFollow\Traits\Follower triat now.
    • Rename event property followingId to followable_id.
    • Added event property followable_type.
    • Added event property user_id.
    • Added trait Overtrue\LaravelFollow\Traits\Follower.

    Full change: https://github.com/overtrue/laravel-follow/commit/59089d5f11a0569f7eecef89bdc96f44fb88cc61

    Migrate from 4.x

    1. Update composer.json:

      overtrue/laravel-follow:^5.0
      

      Then run composer update:

      composer update
      
    2. Update config file config/follow.php with the following code:

      <?php
      
      return [
          /**
           * Use uuid as primary key.
           */
          'uuids' => false,
      
          /*
           * User tables foreign key name.
           */
          'user_foreign_key' => 'user_id',
      
          /*
           * Table name for followers table.
           */
          'followables_table' => 'followables',
      
          /**
           * Model class name for followers table.
           */
      
          'followables_model' => \Overtrue\LaravelFollow\Followable::class,
      ];
      
      
    3. Update the trait Overtrue\LaravelFollow\Followable to Overtrue\LaravelFollow\Traits\Follower:

      - use Overtrue\LaravelFollow\Followable;
      +use Overtrue\LaravelFollow\Traits\Followable;
      +use Overtrue\LaravelFollow\Traits\Follower;
      
      class User extends Authenticatable
      {
          use HasApiTokens;
          use HasFactory;
          use Notifiable; 
      +   use Follower; 
          use Followable;
      
      /// <...>
      
    4. Add doctrine/dbal package:

      Before modifying a column, you must install the doctrine/dbal package using the Composer package manager.

      composer require doctrine/dbal
      
    5. Create a migration file:

      php artisan make:migration update_user_follower_to_followables --table=user_follower
      

      With contents:

      public function up()
      {
          Schema::rename('user_follower', 'followables');
      
          Schema::table('followables', function (Blueprint $table) {
              $table->renameColumn('following_id', 'followable_id');
              $table->renameColumn('follower_id', config('follow.user_foreign_key', 'user_id'));
              $table->string("followable_type")->default(addslashes((new User)->getMorphClass()));
              $table->index(config('follow.user_foreign_key', 'user_id'));
              $table->index(['followable_type', 'accepted_at']);
          });
      }
      
    6. Run migrate:

      php artisan migrate
      
    7. Done.

    Source code(tar.gz)
    Source code(zip)
  • 4.1.0(Apr 6, 2022)

    • Fixed the problem of duplicate data insertion #166
    • Added approvedFollowings/notApprovedFollowings/approvedFollowers/notApprovedFollowers relations #167 .

    Full Changelog: https://github.com/overtrue/laravel-follow/compare/4.0.0...4.1.0

    Source code(tar.gz)
    Source code(zip)
  • 4.0.0(Feb 10, 2022)

  • 3.1.1(Jan 23, 2022)

    What's Changed

    • Disable un-published migration by @zombozo12 in https://github.com/overtrue/laravel-follow/pull/169

    New Contributors

    • @zombozo12 made their first contribution in https://github.com/overtrue/laravel-follow/pull/169

    Full Changelog: https://github.com/overtrue/laravel-follow/compare/3.1.0...3.1.1

    Source code(tar.gz)
    Source code(zip)
  • 3.1.0(Nov 4, 2021)

    Order by followers count

    You can query users order by followers count with following methods:

    • orderByFollowersCountDesc()
    • orderByFollowersCountAsc()
    • orderByFollowersCount(string $direction = 'desc')

    example:

    $users = User::orderByFollowersCountDesc()->get();
    $mostPopularUser = User::orderByFollowersCountDesc()->first();
    
    Source code(tar.gz)
    Source code(zip)
  • 3.0.0(Jun 8, 2021)

  • 2.4.0(Jun 8, 2021)

  • 2.1.0(Apr 18, 2020)

  • 2.0.0(Apr 10, 2020)

    Updated

    • Updated relation table user_follower
    • Rename Overtrue\LaravelFollow\Traits\CanFollow to Overtrue\LaravelFollow\Traits\Followable

    Removed

    • Removed Overtrue\LaravelFollow\Traits\CanBeFollowed
    • Removed Favorite feature and move to overtrue/laravel-favorite
    • Removed Like feature and move to overtrue/laravel-like
    • Removed Subscribe feature and move to overtrue/laravel-subscribe
    • Removed Vote feature.
    • Removed Bookmark feature.
    • Removed events:
      • Overtrue\LaravelFollow\Events\RelationAttaching
      • Overtrue\LaravelFollow\Events\RelationAttached
      • Overtrue\LaravelFollow\Events\RelationDetaching
      • Overtrue\LaravelFollow\Events\RelationDetached
      • Overtrue\LaravelFollow\Events\RelationToggling
      • Overtrue\LaravelFollow\Events\RelationToggled
    Source code(tar.gz)
    Source code(zip)
Owner
安正超
Keep calm and coding.
安正超
GeoLocation-Package - This package helps you to know the current language of the user, the country from which he is browsing, the currency of his country, and also whether he is using it vpn

GeoLocation in PHP (API) ?? ?? ?? This package helps you to know a lot of information about the current user by his ip address ?? ?? ?? This package h

Abdullah Karam 4 Dec 8, 2022
A laravel package to generate model hashid based on model id column.

Laravel Model Hashid A package to generate model hash id from the model auto increment id for laravel models Installation Require the package using co

Touhidur Rahman 13 Jan 20, 2022
A package to filter laravel model based on query params or retrieved model collection

Laravel Filterable A package to filter laravel model based on query params or retrived model collection. Installation Require/Install the package usin

Touhidur Rahman 17 Jan 20, 2022
cybercog 996 Dec 28, 2022
A laravel package to handle sanitize process of model data to create/update model records.

Laravel Model UUID A simple package to sanitize model data to create/update table records. Installation Require the package using composer: composer r

null 66 Sep 19, 2022
Laravel-model-mapper - Map your model attributes to class properties with ease.

Laravel Model-Property Mapper This package provides functionality to map your model attributes to local class properties with the same names. The pack

Michael Rubel 15 Oct 29, 2022
Allow your model to record the creation, update and deletion of user fingerprints in laravel packages

This laravel package will allow your models to record the the created, updated and deleted by User FingerPrints

Managemize 4 Mar 11, 2022
Laravel 2-Step Verification is a package to add 2-Step user authentication to any Laravel project easily.

Laravel 2-Step verification is a package to add 2-Step user authentication to any Laravel project easily. It is configurable and customizable. It uses notifications to send the user an email with a 4-digit verification code. Laravel 2-Step Authentication Verification for Laravel. Can be used in out the box with Laravel's authentication scaffolding or integrated into other projects.

Jeremy Kenedy 204 Dec 23, 2022
Smeify is a Stable Automated Solution for Airtime and Data businesses in Nigeria, this package helps you integrate smeify easily into your laravel application.

Smeify is a Stable Automated Solution for Airtime and Data businesses in Nigeria, this package helps you integrate smeify easily into your laravel application.

Ogundiran Adewale Charles 2 Jul 27, 2022
Add settings to any Laravel model.

Laravel Property Bag Simple settings for Laravel apps. Easily give multiple resources settings Simple to add additional settings as your app grows Set

Zach Leigh 80 Aug 8, 2022
Add eloquent model events fired after a transaction is committed or rolled back

Laravel Transactional Model Events Add transactional events to your eloquent models. Will automatically detect changes in your models within a transac

Mark van Duijker 62 Dec 22, 2022
Laravel-OvalFi helps you Set up, test, and manage your OvalFi integration directly in your Laravel App.

OvalFi Laravel Package Laravel-OvalFi helps you Set up, test, and manage your OvalFi integration directly in your Laravel App. Installation You can in

Paul Adams 2 Sep 8, 2022
This package lets you add uuid as primary key in your laravel applications

laravel-model-uuid A Laravel package to add uuid to models Table of contents Installation Configuration Model Uuid Publishing files / configurations I

salman zafar 10 May 17, 2022
Save Model is a Laravel package that allows you to save data in the database in a new way.

Save Model is a Laravel package that allows you to save data in the database in a new way. No need to worry about $guarded and $fillable properties in the model anymore. Just relax an use Save Model package.

Laratips 27 Mar 2, 2022
A simple laravel package to handle multiple key based model route binding

Laravel Model UUID A simple package to handle the multiple key/column based route model binding for laravel package Installation Require the package u

null 13 Mar 2, 2022
A simple Laravel event log package for easy model based logging.

Karacraft Logman A simple Model Event Logging Package Usage Installation composer require karacraft/logman Migrate php artisan migrate Publish php a

Karacraft 0 Dec 28, 2021
This Package helps you in laravel application to log all desired activity for each request from request entry point to generate response at a single snapshot.

Laravel Scenario Logger This Package helps you in laravel application to log all desired activity for each request from request entry point to generat

Mehrdad Mahdian 6 Sep 27, 2021
Laravel Grid is a package that helps you display table data.

Laravel Grid Laravel Grid is a package that helps you display table data. I could not find package that would satisfy my needs so I decided to write o

null 9 Nov 29, 2022
Keyword Generator Tool helps you discover keyword opportunities related to your query input.

This plugin simply helps you discover keyword opportunities related to your query input. Installation Download the zip file of the repository or clone

WP Refers 1 May 3, 2022