GithubHelp home page GithubHelp logo

hootlex / laravel-friendships Goto Github PK

View Code? Open in Web Editor NEW
700.0 35.0 150.0 120 KB

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

License: MIT License

PHP 100.00%
laravel eloquent friend-requests friend-groups friendships

laravel-friendships's People

Contributors

arubacao avatar bryant1410 avatar clarkewing avatar davidavz avatar dczajkowski avatar gitter-badger avatar hootlex avatar irazasyed avatar kainxspirits avatar nahid avatar nikolaynesov avatar nilportugues avatar physio avatar stephane-monnot avatar vedmant avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

laravel-friendships's Issues

Recipient of a Blockade can block Sender to bypass Blockade

Hey,

currently, it is possible for the recipient of a blockade to block the sender and thereby replacing the old 'friendship' entry with one where recipient and sender are swapped. Then he can delete 'his' blockade.

Reason is, that in blockFriend the following code does not care about the kind of relationship between both models:

// if there is a friendship between two users delete it
$this->findFriendship($recipient)->delete();

Instead, only friendships which are not of type blocked or those with $this as sender should be deleted, effectively allowing two entries in the database for a relation between two models if both models block each other (with swapped sender and recipient).

Notice that this requires further changes in other places, as most of the current code assumes at most one database entry per pair of models. At least, unblockFriend must be changed as well to only delete a blockade with $this as sender and $recipient as recipient.

EagerConstraints?

Can I do something like that? ---> User::with('friends')->find(1);

denyFriendRequest

Hi There,

So if one of my users sent a friend request to another and the user denies the friend request it turns the status to 2 in database, however shouldn't the user have the option to resend the friend request again? this is not working, as soon as the status is set to 2 the user cannot send any more friend request to specific user.

group join

controller:
public function add_member($group_id,$friend_id){
$user = Auth::user();
$group_name=user_group::find($group_id);
$friend=User::find($friend_id);
$user->groupFriend($friend, $group_name);
}

config/friendships.php
'groups' => [
0 => [
'slug'=> 'acquaintances',
'name'=> 'Acquaintances'
],
1 => [
'slug'=> 'close_friends',
'name'=> 'Close Friends'
],
2 => [
'slug'=> 'family',
'name'=> 'My Super Family'
]
]

its give an error Illegal offset type
what will i do?

Jr. Question

Hi Hootlex. First of all, thank you very much for all the hard work on this project.

I'm new to coding, and i'm having some issues i wish you can help me.

In mi UserController.php i have:

public function view($id)
{
$user = User::find(Auth::user()->id);
$recipient = User::find($id);
$posts = Post::where("user_id", "=", $recipient->id)->get();
return view('userviews.userfriend', compact('user', 'posts','recipient'));
}

My problem is that when visiting a profile page, for example: http://localhost:8000/23 (where 23 is the id) if i'm visiting the profile page of the logged user, both $user and $recipient are the same id and then it's impossible to use the acceptRequest and so on functions.

How can i solve this?

Sorry if the question it's to stupid, and thank you for your time.

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?

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.

PostgreSQL findFriendships method issue

I'm using this package with PostgreSQL and this is my error when i call findFriendships() method

SQLSTATE[42883]: Undefined function: 7 ERROR: operator does not exist: smallint ~~ unknown
LINE 1: select * from "friendships" where "status" LIKE $1 and (("se...
^
HINT: No operator matches the given name and argument type(s). You might need to add explicit type casts. (SQL: select * from "friendships" where "status" LIKE 1 and (("sender_id" = 1 and "sender_type" = App\User) or ("recipient_id" = 1 and "recipient_type" = App\User)))

It seems that we can't use the LIKE operator on a smallint column type isn't it?

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.

ERROR MODELS

Error
BadMethodCallException in Builder.php line 2508:
Call to undefined method Illuminate\Database\Query\Builder::getAllFriendships()

app/user.php
`<?php

namespace App;
use Hootlex\Friendships\Traits\Friendable;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable
{

use Notifiable, Friendable;

/**
 * The attributes that are mass assignable.
 *
 * @var array
 */
protected $fillable = [
    'name', 'email', 'password',
];

/**
 * The attributes that should be hidden for arrays.
 *
 * @var array
 */
protected $hidden = [
    'password', 'remember_token',
];

}
My Controllernamespace App\Http\Controllers;
use DB;

use Illuminate\Foundation\Auth\User;
use Illuminate\Http\Request;
use \App\Access_token;
$recipient = User::find(1);
var_dump($recipient->getAllFriendships());`

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

group join

i have some problem in join a friend in a group
$user = Auth::user();
$group_name=user_group::find($group_id);
$friend=Friendship::find($friend_id);
$user->groupFriend($friend, $group_name);

I have not any idea for the parameter in groupFriend($friend, $group_name);

its give error
Argument 1 passed to Illuminate\Database\Grammar::columnize() must be of the type array, string given, called in /var/www/html/krug_me/vendor/laravel/framework/src/Illuminate/Database/Query/Grammars/Grammar.php on line 131 and defined

Non-reciprocal Friendships

I've been looking for something closer to a 'moderated follow' system rather than a 'friend' system.

The way I envision it:

  • User A requests to follow a User B
  • User B accepts/denies request
  • If accepted, there are 2 scenarios:
    • Mutually accepted: User A now follows User B AND User B follows User A
    • Non-mutually accepted: User A now follows User B, but User B does NOT follow User A
      • Later, User B may follow User A without moderation

In essence, it's "I need to approve that you follow me, but I don't necessarily have to follow you back"

Is this something that you can see within the scope of this project, or would it be best for me to fork it? I see that bypit asked something else similar, do you know if that went anywhere?

I'd like to try to do this myself, but I can't seem to get the tests to pass. The error I get is:

Call to undefined function CreateUser()

I am in this directory:

~/Sites/laravel-application/vendor/hootlex/laravel-friendships 

and running this command:

../../bin/phpunit

Can you provide direction with this?

[bug] User sending the friend request can accept it to be friends

There is a bug with your sql statements that allows the person sending the friend request to accept it because it uses the findFriendship method.

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

uses

public function scopeBetweenModels($query, $sender, $recipient)
    {
        return $query->where(function ($q) use ($sender, $recipient) {
                    $q->whereSender($sender)->whereRecipient($recipient);
                })->orWhere(function ($q) use ($sender, $recipient) {
                    $q->whereSender($recipient)->whereRecipient($sender);
                });
    }

The problem is that this method returns the row if the recipient is either the sender OR the recipient. (if that makes sense). And so, this allows the sender to then accept it since it is matching either them as the sender OR the recipient and then it does an update on that row.

Friends since?

How would I go about extending getFriends() to include an additional attribute which says when a user became friends with another user?

I could write an additional method, but I want to avoid the N+1 query issue.

Friendship types

Hi,
Is there any way to set friendship type like "Close friends/Friends/Connections". I guess it requires an extra integer pivot table column like "type"? Or is there a better approach?

Groups in config

Right now we define groups in config this way:

'groups' => [
        'acquaintances' => 0,
        'close_friends' => 1,
        'family' => 2
    ]

It means that developer has to associate a name to each group somewhere else based on slug.
for ex:

[
...
'close_friends' => 'Close Friends',
...
]

What do you think if we let developer specify public names right in the config.
I see 2 ways of doing this.

  1. Use only slugs like 'best_friend' and not indexes to store a group in DB. It will take more space in DB, but makes it more readable. Then config should look like
'groups' => [
        'acquaintances' => 'Acquaintances',
        'close_friends' => 'Close Friends',
        'family' => 'My Family'
    ]
  1. Use array for each group.
'groups' => [
0 => [
'slug'=> 'acquaintances',
'name'=> 'Acquaintances'
],
1 => [
'slug'=> 'close_friends',
'name'=> 'Close Friends'
],
2 => [
'slug'=> 'family',
'name'=> 'My Super Family'
]
]

What do you think would be a better way?

SQL error. Using with Spark

I am getting the below error when trying to beFriend.

Column not found: 1054 Unknown column 'recipient' in 'where clause'

I have both models. Not sure what I may be doing wrong.

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 ?

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.

Spelling mistake in repository description

@hootlex Could you fix the spelling mistake in repo description please (the missing u in eloquent)?
This package gives Eloquent models the ability to manage their friendships.
Thank you in advance for fixing it.

Status is ignored in Friendable::findFriendships

Hi!
I think u have mistake in Friendable::findFriendships.
When I use method: Friendable::getPendingFriendships it should return all friendships with status=0 but it also return friendships with status=1.

/**
 * @param $status
 *
 * @return \Illuminate\Database\Eloquent\Collection
 */
private function findFriendships($status = '%')
{
    return Friendship::where('status', 'LIKE', $status)
        ->where(function ($q) {
            $q->whereSender($this);
        })
        ->orWhere(function ($q) {
            $q->whereRecipient($this);
        });
}

should be:

/**
 * @param $status
 *
 * @return \Illuminate\Database\Eloquent\Collection
 */
private function findFriendships($status = '%')
{
    return Friendship::where('status', 'LIKE', $status)->where(function ($query) {
        $query->where(function ($q) {
            $q->whereSender($this);
        })->orWhere(function ($q) {
            $q->whereRecipient($this);
        });
    });
}

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.

Any use case or samples ?

It is dead simple to understand and sounds great.
But I can not imagine where and when it is useful...
Could you provide a sample app leveraging this nice package ?

Class 'CreateFriendshipsGroupsTable' not found

I Installed this plugin which is amazing may i add but as i need to keep restructuring my tables as im developing when i try to migrate rollback i get the error in the title.

Confirmed error:
Class 'CreateFriendshipsGroupsTable' not found

how can i fix this?

getPendingFriends

Hey,

We have already got getFriends() function to get Users with Friendship ACCEPTED status and other methods like getMutualFriends(), getFriendsOfFriends() . How about to introduce getPendingFriends to get Users (not friendships model like we do in getPendingFriendships()) ?
I want to show a list of pendings friends with some user info that I need get from the User Model and a button to accept the friendship request with a clean and easy method? What do you think? Or maybe I missed something?

Searching within friends?

Is there a way for me to search within my friends using a column value? E.G.

$user -> getFriends($perPage, $column, $value);

pending friendship request

good morning to all,
why only getFriends() function can have the users list with paginate?
how can I help to create these functions?

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

@hootlex I want to add friend in group.I do not any idea in
$user->groupFriend($friend, $group_name);
what $group_name is realy want.
it give an error as
ErrorException in Friendable.php line 124:
Illegal offset type in isset or empty

Starred friendships

Hi,

have you already thought to develop the starred friendship? For example, i have a list of 100 or more friends, but only 10 of them are starred (also know like bookmark/favourite).

Thanks

Accept friend requests only pending

Hi, using in some tests I found that if I ask a friend request, then that request is denied, if I ask another request (between same users) when the second one is accepted then all requests from that user are accepted, even if they were denied, so I have 2 friends count but with the same user.

In the trait I think could be changed
/** * @param Model $recipient * * @return bool|int */ public function acceptFriendRequest(Model $recipient) { return $this->findFriendship($recipient)->whereRecipient($this)->update([ 'status' => Status::ACCEPTED, ]); }

with
/** * @param Model $recipient * * @return bool|int */ public function acceptFriendRequest(Model $recipient) { return $this->findFriendship($recipient)->where('status', Status::PENDING)->whereRecipient($this)->update([ 'status' => Status::ACCEPTED, ]); }

on line 86

pagination

Hi, awesome package. just one thing

How do I do pagination when a user has a lot of friends.

$user->getFriends()->paginate(20);

Thanks

i better way to use the first() method

Hi,

Thanks for a nice library.
I have a little issue when trying to "pick" some rows in my user table and doing something like this

$recipient = User::where('firstname', 'john')->first(['firstname', 'lastname']);

When i doing
Auth::user()->isFriendWith($recipient) it will say false even if the 2 users is friends.
But if i remove the first('firstname', 'lastname') it works fine.

Is there any way to go around this "issue"? because right now I have to do this to get it to work.

$recipient = User::where('firstname', 'john');
$recipient2 = User::where('firstname', 'john')->first(['firstname', 'lastname']);

Auth::user()->isFriendWith($recipient);

Thanks ๐Ÿ‘

Firing events

Hi

Wouldn't it be nice to have by default event fired for each action?

  • friendship.sent When a friend request is sent
  • friendship.accepted When a friend request is accepted
  • friendship.denied When a friend request is denied
  • friendship.blocked When a friend request is blocked

Let me know if you are interested and I will send a PR

If i block an user, next all befriend request will create duplicates

I tried to use your package and i think that you've done a good work, but i found a bug (i think).

TEST CASE: user "$manOne" (model User) isn't friend with "$girlTwo" (model User)
$manOne->blockFriend($girlTwo); $manOne->befriend($girlTwo); $manOne->befriend($girlTwo); $manOne->befriend($girlTwo);

If you see database table, you'll find 4 rows. I know is not normal a block to non-friend user, but if i'd like a "block" for further friendship requests from an user, this should be a solution.

Thanks for your work.

getPendingFriendships() does fetch all frindschips

Hi,

there is a Problem with getPendingFriendships().
Everytime i use this method, it returns also accepted and blocked Friendships.

So i have to call

$user->getPendingFriendships()
    ->where('recipient_id', $user->id)
    ->where('status', 0);

Or is there an error in my code?

Thanks for this package, it's absolutely amazing

Method to get mutual friends

Hi there, I thought it'd be nice to have a method that would give mutual friends, and maybe even another one giving the count of mutual friends. I'll try to work up some code when I get a chance.

sender_id' cannot be null

I am creating the user vairable, and passing it through to befriend, but am receiving the error below, this is my code:

public function getManageFriendRequests($id, $type, User $user)
{
    $recipient = $user->find($id);
    $sender = Auth::user();

    if($type == 'accept'){
        $user->acceptFriendRequest($recipient);
    }
    elseif($type == 'reject'){
        $user->denyFriendRequest($recipient);
    }
    elseif($type == 'add'){
        $user->befriend($recipient);
    }

}

QueryException in Connection.php line 770:
SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'sender_id' cannot be null (SQL: insert into friendships (recipient_id, recipient_type, status, sender_type, sender_id, updated_at, created_at) values (1, App\User, 0, App\User, , 2017-01-14 14:49:46, 2017-01-14 14:49:46))

What is causing this error? I'm sure I've followed all the instruction?

getFriendRequests with recipient object

Hello,
After sending a friend request I send back a response with my friendrequest:

public function sendFriendRequest(Request $request)
{
$user = Auth::user();

       $recipient = User::where('id', '=', $request->id)->first();


       $user->befriend($recipient);

       $friendRequests = $user->getFriendRequests();

   return  response($friendRequests, 200);
}

How can I get the recipient user object with that response?
I need to display the profile image, full name ... not just sender_id.

Thank you.

Hi hootlex

How can i use this package i'm new to laravel,please help me
thank you

Lumen support

Is this package out of the box compatible with Lumen?

Syntax error or access violation: 1103

Hello! Please help me, error while migrating...

After installing, in migration step, i have an error :

  [Illuminate\Database\QueryException]
  SQLSTATE[42000]: Syntax error or access violation: 1103 Incorrect table name '' (SQL: create table `` (`id` int unsigned not null au
  to_increment primary key, `sender_id` int unsigned not null, `sender_type` varchar(255) not null, `recipient_id` int unsigned not nu
  ll, `recipient_type` varchar(255) not null, `status` tinyint not null default '0', `created_at` timestamp null, `updated_at` timesta
  mp null) default character set utf8 collate utf8_unicode_ci)

  [Doctrine\DBAL\Driver\PDOException]
  SQLSTATE[42000]: Syntax error or access violation: 1103 Incorrect table name ''

  [PDOException]
  SQLSTATE[42000]: Syntax error or access violation: 1103 Incorrect table name ''

I think the problem is in this command ->on(config('friendships.tables.fr_pivot')) :

$table->foreign('friendship_id')
                ->references('id')
                ->on(config('friendships.tables.fr_pivot'))
                ->onDelete('cascade');

Change friendship db table name?

Hey.

I just was curios and wanted to ask, if it was possible to change the table name of the friendships without having to extend the model and creating a custom migration? Its no big deal if not, but I thought I'd bring it up anyway ^^.

Kind regards, Ingwie

Limitation of friendships

Is it possible to add a Limitation of friendships to the package. I mean e.g. that user (A) can only have 10 Friends and User (B) 20. And the Limitations saved in DB

If you can add this, I would be really happy about that

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.