This package gives Eloquent models the ability to manage their friendships.

Overview

Laravel 5 Friendships

Build Status Code Climate Test Coverage Total Downloads Version Software License Join the chat at https://gitter.im/laravel-friendships/Lobby

This package gives Eloquent models the ability to manage their friendships. You can easily design a Facebook like Friend System.

Models can:

  • Send Friend Requests
  • Accept Friend Requests
  • Deny Friend Requests
  • Block Another Model
  • Group Friends

Installation

First, install the package through Composer.

composer require hootlex/laravel-friendships

If you are using Laravel < 5.5, you need to add Hootlex\Friendships\FriendshipsServiceProvider to your config/app.php providers array:

Hootlex\Friendships\FriendshipsServiceProvider::class,

Publish config and migrations

php artisan vendor:publish --provider="Hootlex\Friendships\FriendshipsServiceProvider"

Configure the published config in

config\friendships.php

Finally, migrate the database

php artisan migrate

Setup a Model

use Hootlex\Friendships\Traits\Friendable;
class User extends Model
{
    use Friendable;
    ...
}

How to use

Check the Test file to see the package in action

Send a Friend Request

$user->befriend($recipient);

Accept a Friend Request

$user->acceptFriendRequest($sender);

Deny a Friend Request

$user->denyFriendRequest($sender);

Remove Friend

$user->unfriend($friend);

Block a Model

$user->blockFriend($friend);

Unblock a Model

$user->unblockFriend($friend);

Check if Model is Friend with another Model

$user->isFriendWith($friend);

Check if Model has a pending friend request from another Model

$user->hasFriendRequestFrom($sender);

Check if Model has already sent a friend request to another Model

$user->hasSentFriendRequestTo($recipient);

Check if Model has blocked another Model

$user->hasBlocked($friend);

Check if Model is blocked by another Model

$user->isBlockedBy($friend);

Get a single friendship

$user->getFriendship($friend);

Get a list of all Friendships

$user->getAllFriendships();

Get a list of pending Friendships

$user->getPendingFriendships();

Get a list of accepted Friendships

$user->getAcceptedFriendships();

Get a list of denied Friendships

$user->getDeniedFriendships();

Get a list of blocked Friendships

$user->getBlockedFriendships();

Get a list of pending Friend Requests

$user->getFriendRequests();

Get the number of Friends

$user->getFriendsCount();

Get the number of Pendings

$user->getPendingsCount();

Get the number of mutual Friends with another user

$user->getMutualFriendsCount($otherUser);

Friends

To get a collection of friend models (ex. User) use the following methods:

Get Friends

$user->getFriends();

Get Friends Paginated

$user->getFriends($perPage = 20);

Get Friends of Friends

$user->getFriendsOfFriends($perPage = 20);

Collection of Friends in specific group paginated:

$user->getFriends($perPage = 20, $group_name);

Get mutual Friends with another user

$user->getMutualFriends($otherUser, $perPage = 20);

Friend groups

The friend groups are defined in the config/friendships.php file. The package comes with a few default groups. To modify them, or add your own, you need to specify a slug and a key.

// config/friendships.php
...
'groups' => [
    'acquaintances' => 0,
    'close_friends' => 1,
    'family' => 2
]

Since you've configured friend groups, you can group/ungroup friends using the following methods.

Group a Friend

$user->groupFriend($friend, $group_name);

Remove a Friend from family group

$user->ungroupFriend($friend, 'family');

Remove a Friend from all groups

$user->ungroupFriend($friend);

Get the number of Friends in specific group

$user->getFriendsCount($group_name);

To filter friendships by group you can pass a group slug.

$user->getAllFriendships($group_name);
$user->getAcceptedFriendships($group_name);
$user->getPendingFriendships($group_name);
...

Events

This is the list of the events fired by default for each action

Event name Fired
friendships.sent When a friend request is sent
friendships.accepted When a friend request is accepted
friendships.denied When a friend request is denied
friendships.blocked When a friend is blocked
friendships.unblocked When a friend is unblocked
friendships.cancelled When a friendship is cancelled

Contributing

See the CONTRIBUTING guide.

Comments
  • Add user's personal groups (acquaintances, family, etс.) support

    Add user's personal groups (acquaintances, family, etс.) support

    User can group/ungroup his/her friends with new methods groupFriend & ungroupFriend. Personal groups support added to getAllFriendships, getAcceptedFriendships, getFriendsCount, getFriends methods.

    opened by nikolaynesov 30
  • Install Issue

    Install Issue

    root@ns371466:/var/www/html# composer require hootlex/laravel-friendships Using version ^1.0 for hootlex/laravel-friendships ./composer.json has been updated Loading composer repositories with package information Updating dependencies (including require-dev) Package operations: 1 install, 0 updates, 0 removals

    • Installing hootlex/laravel-friendships (v1.0.21): Downloading (100%) Writing lock file Generating autoload files

    Illuminate\Foundation\ComposerScripts::postUpdate php artisan optimize Generating optimized class loader The compiled services file has been removed.

    root@ns371466:/var/www/html# php artisan vendor:publish --provider="Hootlex\Friendships\FriendshipsServiceProvider" Publishing complete.

    root@ns371466:/var/www/html# php artisan migrate Nothing to migrate.

    Im having a issue where php artisan vendor:publish --provider="Hootlex\Friendships\FriendshipsServiceProvider" isn't really publishing anything.

    Running Laravel 5.4

    opened by HDVinnie 18
  • Reciprocal friendship

    Reciprocal friendship

    Hi,

    I have an idea/question...

    So I acctually want to use this package, but I kinda need something you get 'reciprocal friendship'. So something like Facebook has:

    I sent a friendshiprequest to user B.

    User B accepts the friendship and now we both have each other in our friends list. Because I sent the request, I want to be a friend, and he accepts it, so we both are friends. Any idea how I can do this via your package? Or in a new release?

    question 
    opened by RosiersRobin 13
  • I don't understand how to use this package.

    I don't understand how to use this package.

    Im developing a proffesional network and want the users to connect to each other. I found this package but how to i use it especcialy when you already have the user model which stores all the users. hoa to get sender id and receipt it.

    opened by antweny 12
  • acceptFriendRequest / denyFriendRequest does not work

    acceptFriendRequest / denyFriendRequest does not work

    Hi guys,

    i have successfully installed the package, but unfortunately i cannot use those functions. The send request and the block functions are working so i think the problem comes from the update() method:

    public function acceptFriendRequest(Model $recipient) { return $this->findFriendship($recipient)->whereRecipient($this)->update([ 'status' => Status::ACCEPTED, ]); }

    Do u have any clue why is that ?

    opened by perffy 11
  • Friendship always accepted

    Friendship always accepted

    When I send a friendship request to a model, when I check if a model is friend with another (using $user->isFriendWith($recipient), it will return me always true, even if the request is still pending.

    opened by smokills 9
  • Added three new methods for limit and pagination when getting Friends(accepted)

    Added three new methods for limit and pagination when getting Friends(accepted)

    Get All Friends(accepted) (It returns a collection of friend models not friendships, for example User)

    $user->getAllFriends();
    

    Get Friends(accepted) with Limit

    $user->getFriendsLimited($limit);
    
    Use Case
    $user->getFriendsLimited(5);
    

    This will return only 5 friends.

    Get Friends(accepted) with Pagination

    $user->getFriendsWithPagination($perPage);
    
    Use Case
    $friends = $user->getFriendsWithPagination(5);
    

    This will return a paginator object. To render links

    5.1: Use ->render();
    5.2: Use ->links();
    
    View
    @foreach($friends as $friend)
        <p>{{ $friend->name }}</p>
    @endforeach
    
    {!! $friends->links() !!}
    
    opened by elsodev 8
  • A little help here!

    A little help here!

    I have been using this friends package with an app i am trying to build. As a sender, I can send a friend request to a recipient, log in as a recipient and accept the request.

    From the sender end, I can list the list of friends he sent the request to and build the list of friends using the getAcceptedFriendships() method, looping through the results and getting the recipient details. However when I log in as the recipient, when I do the same, instead of the sender's name being listed, the recipient's name gets listed instead...

    Any ideas as to how to fix this?

    Thanks.

    question 
    opened by darkweb2015 8
  • getAcceptedFriends not returning the user details

    getAcceptedFriends not returning the user details

    When i fetch all accepted friendship and pass to the view the names and id of the friends not showing.

    My controller file

    public function connections ()
            {
                $user = Auth::user();
                $connections = $user->getAcceptedFriendships();;
                return view('users.friendships.connections')->with(compact('connections'));
            }
    

    View file

    @foreach($connections as $user)
         <li>
            <h6>{{$user->name}}</h6>
        </li>
    @endforeach
    

    It displays the list of all accepted friendship without their details like their name.

    I need support

    opened by antweny 7
  • Feature request: get friends of friends

    Feature request: get friends of friends

    This would be really helpful to have, but this is quite complex task with your current DB structure, it's much easier to use two way relation for this, means for each friendship there are two records user_one => user_two and user_two => user_one, this will make complex queries much simpler.

    enhancement 
    opened by vedmant 7
  • FriendshipsTest::user_can_send_a_friend_request BadMethodCallException: Call to undefined method Illuminate\Database\Query\Builder::befriend()

    FriendshipsTest::user_can_send_a_friend_request BadMethodCallException: Call to undefined method Illuminate\Database\Query\Builder::befriend()

    When testing the application im getting de following error:

    `There were 21 errors:

    1. FriendshipsTest::user_can_send_a_friend_request BadMethodCallException: Call to undefined method Illuminate\Database\Query\Builder::befriend()

    /public_html/laravel/vendor/laravel/framework/src/Illuminate/Database/Query/Builder.php:2306 /public_html/laravel/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Builder.php:1388 /public_html/laravel/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Model.php:3500 /public_html/laravel/vendor/hootlex/laravel-friendships/tests/FriendshipsTest.php:17 /public_html/laravel/vendor/hootlex/laravel-friendships/tests/FriendshipsTest.php:17 ` I installed the laravel-friendships and start the test getting the error. Is there is something i did error? Using the new version of laravel.

    opened by spongi07 5
  • Method Illuminate\Events\Dispatcher::fire does not exist

    Method Illuminate\Events\Dispatcher::fire does not exist

    Kindly change this in an updated version as The fire() method is an alias to the dispatch() method. The renaming of this method started way back in the 5.3 to 5.4 upgrade, and is included in the upgrade guide:

    https://laravel.com/docs/5.4/upgrade

    Thanks as we can use this package fro laravel updated versions

    opened by nabilahmed7 3
  • Why getFriends method returns all friends ?

    Why getFriends method returns all friends ?

    Hello,

    Requirement :- to fetch friends of a specific group and I have used getFriends($perPage = 20, $group_name) method.

    Problem :- getFriends($perPage = 20, $group_name) returns all friends of application and also getFriendsCount($group_name) returns count of all friends of application. can you please help me?

    Here is code:

    foreach ($groups as $group) { $group_name = $group->title; $group_connections = $user->getFriends($perPage = 20, $group_name); }

    Thanks in advance!

    opened by roshani3110 4
  • Composer install hootlex requires version ~5.*

    Composer install hootlex requires version ~5.*

    Hi, I have an existing laravel project and wanted to add a new package for creating pdf. Unfortunately I always get this error when I require any package with composer

      [RuntimeException]
      Could not load package hootlex/laravel-friendships in http://repo.packagist.org: [UnexpectedValueException] Could not parse version constraint ~5.*: Invalid version string "~5.*"
    
      [UnexpectedValueException]
      Could not parse version constraint ~5.*: Invalid version string "~5.*"
    

    It is very weird because of the version, when I remove the package I can install the pdf package. But I cannot install hootlex/laravel-friendships package anymore as I'm getting the same error as described above.

    opened by swietek 13
  • Replace usage of  deprecated Illuminate\Events\Dispatcher::fire()

    Replace usage of deprecated Illuminate\Events\Dispatcher::fire()

    I'm always getting an error when trying to seed my database causd be the method $user->befriend($arg);

    My research has shown that this method is outdated. My updates did not help me to get rid of this error. Will it be fixed?

    ` Symfony\Component\Debug\Exception\FatalThrowableError : Call to undefined method Illuminate\Events\Dispatcher::fire()

    at /var/www/my-api/vendor/laravel/framework/src/Illuminate/Support/Facades/Facade.php:239 235| if (! $instance) { 236| throw new RuntimeException('A facade root has not been set.'); 237| } 238|

    239| return $instance->$method(...$args); 240| } 241| } 242|

    Exception trace:

    1 Illuminate\Support\Facades\Facade::__callStatic("fire") /var/www/my-api/vendor/hootlex/laravel-friendships/src/Traits/Friendable.php:35

    2 App\User::befriend(Object(App\User)) /var/www/my-api/database/seeds/UserTableSeeder.php:56

    Please use the argument -v to see more details.

    Whoops\Exception\ErrorException : Module 'sqlite3' already loaded

    at Unknown:0 1|

    Exception trace:

    1 Whoops\Run::handleError("Module 'sqlite3' already loaded", "Unknown") /var/www/my-api/vendor/filp/whoops/src/Whoops/Run.php:408

    2 Whoops\Run::handleShutdown() [internal]:0 `

    opened by jwittekind 4
Releases(v1.0.24)
Owner
Alex Kyriakidis
Developer - Teacher - Author- Consultant
Alex Kyriakidis
A Laravel package making a diagram of your models, relations and the ability to build them with it

Laravel Schematics This package allows you to make multiple diagrams of your Eloquent models and their relations. It will help building them providing

Maarten Tolhuijs 1.4k Dec 31, 2022
An Eloquent Way To Filter Laravel Models And Their Relationships

Eloquent Filter An Eloquent way to filter Eloquent Models and their relationships Introduction Lets say we want to return a list of users filtered by

Eric Tucker 1.5k Jan 7, 2023
An Eloquent Way To Filter Laravel Models And Their Relationships

Eloquent Filter An Eloquent way to filter Eloquent Models and their relationships Introduction Lets say we want to return a list of users filtered by

Eric Tucker 1.5k Dec 30, 2022
A small package for adding UUIDs to Eloquent models.

A small package for adding UUIDs to Eloquent models. Installation You can install the package via composer: composer require ryangjchandler/laravel-uu

Ryan Chandler 40 Jun 5, 2022
Laravel package to search through multiple Eloquent models.

Laravel package to search through multiple Eloquent models. Supports sorting, pagination, scoped queries, eager load relationships and searching through single or multiple columns.

Protone Media 845 Jan 1, 2023
An opinionated package to create slugs for Eloquent models

Generate slugs when saving Eloquent models This package provides a trait that will generate a unique slug when saving any Eloquent model. $model = new

Spatie 1.1k Jan 4, 2023
A package to generate YouTube-like IDs for Eloquent models

Laravel Hashids This package provides a trait that will generate hashids when saving any Eloquent model. Hashids Hashids is a small package to generat

Λгi 25 Aug 31, 2022
Package with small support traits and classes for the Laravel Eloquent models

Contains a set of traits for the eloquent model. In future can contain more set of classes/traits for the eloquent database.

Martin Kluska 3 Feb 10, 2022
Kalibrant - a package that provides a simple way to manage your models settings

Introduction For your laravel 9.x applications, Kalibrant is a package that provides a simple way to manage your models settings. It is a simple way t

Starfolk 3 Jun 18, 2022
Easily generate URLs to Minecraft avatars with the ability to switch between services

Minecraft Avatar URLs This library provides PHP utilities to generate URLs to Minecraft Avatars in different formats with the ability to easily change

Gigadrive UG 3 Aug 11, 2022
This package gives you a set of conventions to make the most out of Hotwire in Laravel

Introduction This package gives you a set of conventions to make the most out of Hotwire in Laravel (inspired by the turbo-rails gem). There is a comp

Tony Messias 665 Jan 2, 2023
Package for Laravel that gives artisan commands to setup and edit environment files.

Setup and work with .env files in Laravel from the command line NOTE: This doesn't work with Laravel 5 since .env files were changed. This is for Lara

Matt Brunt 6 Dec 17, 2022
Easy creation of slugs for your Eloquent models in Laravel

Eloquent-Sluggable Easy creation of slugs for your Eloquent models in Laravel. NOTE: These instructions are for the latest version of Laravel. If you

Colin Viebrock 3.6k Dec 30, 2022
Sortable behaviour for Eloquent models

Sortable behaviour for Eloquent models This package provides a trait that adds sortable behaviour to an Eloquent model. The value of the order column

Spatie 1.2k Dec 22, 2022
Automatically validating Eloquent models for Laravel

Validating, a validation trait for Laravel Validating is a trait for Laravel Eloquent models which ensures that models meet their validation criteria

Dwight Watson 955 Dec 25, 2022
Laravel Ban simplify blocking and banning Eloquent models.

Laravel Ban Introduction Laravel Ban simplify management of Eloquent model's ban. Make any model bannable in a minutes! Use case is not limited to Use

cybercog 879 Dec 30, 2022
cybercog 996 Dec 28, 2022
Create presenters for Eloquent Models

Laravel Presentable This package allows the information to be presented in a different way by means of methods that can be defined in the model's pres

The Hive Team 67 Dec 7, 2022
Use auto generated UUID slugs to identify and retrieve your Eloquent models.

Laravel Eloquent UUID slug Summary About Features Requirements Installation Examples Compatibility table Alternatives Tests About By default, when get

Khalyomede 25 Dec 14, 2022