Giter VIP home page Giter VIP logo

multicaret / laravel-acquaintances Goto Github PK

View Code? Open in Web Editor NEW
797.0 17.0 71.0 201 KB

This package gives Eloquent models the ability to manage friendships (with groups), followships along with Likes, favorites..etc.

Home Page: https://laravel-news.com/manage-friendships-likes-and-more-with-the-acquaintances-laravel-package

License: MIT License

PHP 100.00%
laravel friend-requests friendship friend-groups mutual-friends pending-requests acquaintances eloquent-models vote laravel-acquaintances

laravel-acquaintances's People

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

laravel-acquaintances's Issues

UUID instead of id

is it possible to update the docs on what to change in order to use UUIDs instead if inc-id ?

Error in CanVote.php: str_plural

Hello,

Is this package still maintained? If so, I discovered a bug when using this package on Laravel 8. In CanVote.php, there's an error on the following line:

return Interaction::attachRelations($this, str_plural($type), $targets, $class);

It looks like the str_plural function is no longer supported in Laravel 8. The str_plural function needs to be updated to Str::plural.

Usage with livewire and notifications

Hey, Users in my app can send friend requests to other users, When they click the add friend button I would like to notify the user that got send the friend request a notification. But how would I go using the package together with Livewire to send a notification when a user gets a friend request. Is their any build in functionality for usage with livewire ?

Enhancements

first many thanx for the package, it did help alot, however there is a room for improvements ex.

  • the friendship group could be saved into db with a seeder & use it like any other relation without the need for accessing the config & making a lockup using the id
  • atm the models are not extendable, so to get around that we can add the models namespaces to the config.
  • update the events in the readme with their payload/params.
  • update the readme with a section on how to use UUID instead of IDs for the relations
  • add a couple of helper methods like toggleFriendship
  • this section might be wrong, because you cant group a friend unless it was accepted first

i'll be more than happy to submit a PR for any.

anonymous block user/model (regardless of friendship status)

SOLVED - I just didn't understand it. the friendships is creaed at the time of blocking. it's perfectly good as is. (althougha a toggleBlock() would be nice to have )

Hi, is there a way to implement this so that a user can block another user regardless of friendship status?
as I understand the docs, to block someon, they must first be a friend. Blocks are also something you may wish impose of another user to prevent seeing thier posts.

DB migration fails on users.id foreign key

In Laravel 5.8, When running the migration files that come with the package it throws an error when running the 2018_06_14_000000_create_acquaintances_interactions_table migration:

Illuminate\Database\QueryException  : SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint (SQL: alter table `interactions` add constraint `interactions_user_id_foreign` foreign key (`user_id`) references `users` (`id`) on delete cascade on update cascade)

This is because the users.id field is no longer a unsignedInteger, it has been changed to an unsignedBigInteger.

Changing the migration file line 19, from this:

$table->unsignedInteger('user_id')->index();

To this:

$table->unsignedBigInteger('user_id')->index();

Fixes the problem.

I'm not sure if you'd want to add this change to your package, as I think it would then break on older versions of Laravel, that still use the unsignedInteger ID field type.

help with using isFollowedBy within a get()

Hi,
I'm struggling to get all models where they are followed by the current Auth::user

my repository is using:

$boards = Board::withCount('posts')
->isFollowedBy($user)
->paginate($this->pagination);

the error I get is: Call to undefined method Illuminate\Database\Eloquent\Builder::isFollowedBy()

However, when I try:

$boards = Board::isFollowedBy($user)
->paginate($this->pagination);

the error is: Non-static method App\Models\Board::isFollowedBy() should not be called statically

how would I get all models where a user has followed (or subscribed, liked etc.)

A blocked user can unlock himself

Current implementation of acceptFriendRequest doesn't check the status of existing friendship between users.
This is a serious security issue if developper not aware of this behavior and simply implement controller that maps 1 to 1 acquaintances methods.

// Let's create two friends
[$user, $friend] = User::factory(2)->create();
$user->befriend($friend);
$friend->acceptFriendRequest($user);
$this->assertTrue($user->isFriendWith($friend)); // OK 

// Things goes bad, user blocks friend
$user->blockFriend($friend);
$this->assertFalse($user->isFriendWith($friend)); // OK
        
// Later.. malicious friend perform an acceptFriendRequest
$friend->acceptFriendRequest($user);
$this->assertFalse($user->isFriendWith($friend)); // Failed asserting that true is false.

As befriend() method check for precondition (it calls canBefriend()), we would expect from acceptFriendRequest the same level of verification.

Method Illuminate\Database\Eloquent\Collection::whereRecipient does not exist.

I have in a controller ,both current_user and friend have the expected users.

        $current_user = Auth::user();
        $friend = User::findOrFail($friend_id);

        if(!$current_user->isBlockedBy($friend)){

It fails in the if condition with the message

Method Illuminate\Database\Eloquent\Collection::whereRecipient does not exist.

Below is the method in the Friendable trait,what is strange that it used to work. I have the lastest version (3.5.3),Laravel 7

public function hasBlocked(Model $recipient)
    {
        return $this->friends()->whereRecipient($recipient)->whereStatus(Status::BLOCKED)->exists();
    }

Thanks.

$user->getFriends() pagination problem

Hi!

Thanks for this amazing package. I have a problem with pagination when using getFriends method. But I have seen that this method has parameters in Friendable trait.

Error:
Livewire component's [friends-list] public property [friends] must be of type: [numeric, string, array, null, or boolean]. Only protected or private properties can be set as other types because JavaScript doesn't need to access them.

My code:

namespace App\Http\Livewire;

use Livewire\Component;

class FriendsList extends Component
{

    public $perPage = 6;

    public $user;

    public $friends;

    protected $listeners = [
        'load-more-friends' => 'loadMoreFriends'
    ];

    public function mount($user)
    {
        $this->user = $user;
    }

    public function loadMoreFriends()
    {
        $this->perPage = $this->perPage + 5;
    }

    public function render()
    {
        $this->friends = $this->user->getFriends($this->perPage); // getFriends($perPage = 0, $groupSlug = '', array $fields = ['*'])
        return view('livewire.friends-list');
    }
}

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

➜  New git:(master) ✗ php artisan migrate
Migrating: 2021_08_23_104103_create_acquaintances_friendships_groups_table

   Illuminate\Database\QueryException

  SQLSTATE[42000]: Syntax error or access violation: 1103 Incorrect table name '' (SQL: create table `` (`id` bigint unsigned not null auto_increment primary key, `friendship_id` bigint unsigned not null, `friend_type` varchar(255) not null, `friend_id` bigint unsigned not null, `group_id` int unsigned not null) default character set utf8mb4 collate 'utf8mb4_unicode_ci')

I have tried everything still getting this error

New config option: connection

I am running into an issue when using multiple connections in one app.
I need to be able to specify the $connection attribute for the models.
Is this possible with the config file?

How to paginate followers?

I tried with

$this->user->followers->paginate(10);

But throws

Method Illuminate\Database\Eloquent\Collection::paginate does not exist.

problem with denying where a subsequent request being accepted will result in two friendships

Hi,
I've noticed a problem with deniying requests.

Because you set the status to 'denied' and don't include an isDeniedBy() method, we can't [out of the box] prevent a sender from re-befriending.

This problem is then compounded when a recipient denies or blocks a sender, then the sender subsequently re-befriends, a new entry is created with the status pending (thus creating two entires for sender_id = x & recipient_id = y) - once that recipient accepts (or blocks etc) the sender, both enties become syncronised (accepted or blocked etc).

This results in multiple valid friendships for a single status

  • A (less than desireable) workaround is to ignore all deny methods and use unfriend instead. This will remove the befriend request thus preventing these multiples
  • If you'd prefer to prevent re-befriendings after the first denial then use blockFriendRequest instead of unfriend. This will maintain a status you can work with.

Laravel 8 Support

It would be great if this package update its support to Laravel 8!

Migrations not working after upgrade

SQLSTATE[HY000]: General error: 1005 Can't create table `laravel_dev`.`friendship_groups` (errno: 150 "Foreign key constraint is incorrectly formed") (SQL: alter table `friendship_groups` add constraint `friendship_groups_friendship_id_foreign` foreign key (`friendship_id`) references `friendships` (`id`) on delete cascade)

I have synced the config file, cleared the cache and the updated migrations.

time limited blocking (suspension)

Hi, is there a means to have a time limited block so we can suspend / mute / pause a friendship?

A "suspend" trait that accepts a duration that this an auto expiring blocking.
$user->suspend($target,$datetime) // set $datetime of expiry
$user->suspendedUntil($target) // returns datetime of expiry
$user->unsuspend($target) // deletes suspension
$user->hasSuspended($target) // returns bool
$target->isSuspendedBy($user) // returns bool

you get the idea ;)

"Comment" interaction on User/Model ?

Hi there !

Looks great, I'm wondering if you have plan to add a "Comment" interaction on User/Model ?
Or any suggestion on how to implement this ?

Thanks , Denis

`Illuminate\Events\Dispatcher::fire()` removed in 5.8

In Laravel 5.8, the Illuminate\Events\Dispatcher::fire() method has been deprecated removed from the codebase, meaning that whenever this package triggers and event it throws a fatal error:

Call to undefined method Illuminate\Events\Dispatcher::fire()

This can be fixed by replacing::fire() with ::dispatch(). I'm happy to put a pull request together if you're okay with that?

Unknown column 'updated_at'

Upgrading to 3.4.3 introduced 2 issues:

Method getFullModelName not found (I checked the pull request which fixes it correctly).
But the other pending issue is

Column not found: 1054 Unknown column 'updated_at' in 'field list' (SQL: insert into `interactions` (`subject_id`, `user_id`, `created_at`, `subject_type`, `relation`
, `updated_at`) values (1, 5, 2021-03-17 10:33:16, App\Models\Comment, upvote, 2021-03-17 10:33:16))

whenever I call the upvote() method.

missing isDeniedBy method

Hi,
In the name of completeness (and becasue I'd like it) it would be great to have an isStatusBy for evey status possible. e.g isDeniedBy()

thanks.

Remove attributes from traits?

Hi @msk286, could we please remove the attributes within the traits by any chance? Right now, when you call "toArray" on the model it runs all the methods of the model and thus fires unneeded SQL queries. Maybe as part of a new major release since it would be a breaking change. If users need it, they can anyway easily define it themselves because the helper methods exist.

Add target type to events

When an event is dispatched, and the action sent is by id instead of an eloquent model, there is no way to know what type the model is.

Take cancelVote for example,

In the trait, you have:

    public function upvote($targets, $class = __CLASS__)
    {
        Event::dispatch('acq.vote.up', [$this, $targets]);

        return $this->vote($targets, 'upvote', $class);
    }

I suggest we add $class to the array so that in the listener, we can grab the eloquent model if only the id is sent.

This needs to be applied to all traits in the library. I can open a PR if needed. No breaking change is needed.

Let me know your thoughts.

Additional scopes like trending, period scopes, etc.

It would be cool to add additional scopes, the popular scope already exists, however it doesn't have features like getting trending objects and/or objects popular in a certain period.

I'll do my best to make a PR for this to include the scopes based on the already existing popular, however I would like to ask your opinion about this one/here your ideas first. :)

Error: Class "App\User" not found

Performed a composer update to a running project and have isolated the issue to the "Like" components.
Prior to this, the project worked perfectly.

Receive Error Class "App\User" not found...

Example call that resolves in this error:
$nugget->isLikedBy(auth()->user())
or
$nugget->likersCountReadable()

Stack Trace:
[2021-07-11 20:26:53] local.ERROR: Class "App\User" not found (View: /var/www/html/resources/views/nugget/nuggets.blade.php) {"view":{"view":"/var/www/html/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Concerns/HasRelationships.php","data":[]},"userId":1,"exception":"[object] (Facade\Ignition\Exceptions\ViewException(code: 0): Class "App\User" not found (View: /var/www/html/resources/views/nugget/nuggets.blade.php) at /var/www/html/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Concerns/HasRelationships.php:745)
[stacktrace]
#0 /var/www/html/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Concerns/HasRelationships.php(549): Illuminate\Database\Eloquent\Model->newRelatedInstance()
#1 /var/www/html/vendor/multicaret/laravel-acquaintances/src/Traits/CanBeLiked.php(33): Illuminate\Database\Eloquent\Model->morphToMany()
#2 /var/www/html/vendor/multicaret/laravel-acquaintances/src/Interaction.php(69): App\Models\Nugget->likers()
#3 /var/www/html/vendor/multicaret/laravel-acquaintances/src/Traits/CanBeLiked.php(22): Multicaret\Acquaintances\Interaction::isRelationExists()
#4 /var/www/html/resources/views/nugget/nuggets.blade.php(122): App\Models\Nugget->isLikedBy()

Versions

PHP Version: 8.0.1
app()->version() returns: 8.49.2
Composer.lock:
"name": "multicaret/laravel-acquaintances",
"version": "v3.5.4",

It looks like the change may be related to the June 28th namespace update.
Any help would be greatly appreciated!

How would i retunred a list of Posts and their likes?

Lets say I have

 `$latest_posts= Post::with('user')->latest()->paginate(15);`

How would I associate their likes(if they exist)? .I could do an awkward JOIN on subject_type and subject_id in the interactions table but that seems like caveman mysql. Thanks.

Like: Reaction type support.

Is there any way I can give the reaction type of 'like'? Like on Facebook.

Ex. $user->like($targets, 'reaction');
Reaction types: 'Like', 'Love', 'Haha'...

Unknown column issue

Hi, First of all , thanks for this package.
There's a very strange issue when I try to add like, check if the target has been like be auth API user
Here is what I got:

SQLSTATE[42S22]: Column not found: 1054 Unknown column "interactions.api_auth_id" in "where clause" (SQL: select exists(select * from "topics" inner join "interactions" on "topics"."id" = "interactions"."subject_id" where "interactions"."api_auth_id" = 1 and "interactions"."subject_type" = App\\Models\\Topic and "interactions"."relation" = like and "subject_id" = 1 and "topics"."deleted_at" is null) as "exists")","

Can we eager load the friend/follower/favorite count?

Hi, @mkwsra , first of all, thank you for bringing this package to the community. We are grateful for your contribution.

One thing I want to ask can we eager load it? Because right now, when we load the models in tremondous amount, the queries start to get crazy 😅.

Here are the screenshot of the queries. 104 queries happened for each model.
Screen Shot 2021-05-18 at 20 26 44

Feature: Followers you know

It would be great if we have "Followers you know" similar to mutual friends

image

And also the ability to block followers also would be awesome 😃

{{ $model->likers()->count() }} Eager ?

Models/Thread.php
`
class Thread extends Model
{
use HasFactory;

public function comments()
{
    return $this->morphMany(Comment::class, 'commentable')->whereNull('parent_id');
}

}
`

Models/Comment.php
`
class Comment extends Model
{
use HasFactory, CanBeLiked;

protected $with = ['user', 'replies'];

public function commentable()
{
    return $this->morphTo();
}

public function user()
{
    return $this->belongsTo(User::class);
}

//zi
public function replies()
{
    return $this->hasMany(Comment::class, 'parent_id')->oldest();
}

}
`

Livewire/Comments.php
`class Comments extends Component
{
public $model;

public function render()
{

    return view('livewire.comment.comments', [
        'comments' => $this->model
                            ->comments()
                            ->paginate(10)
    ]);
}

}`

Livewire/comment.php
`
class Comment extends Component
{
public $comment;

public function render()
{
    return view('livewire.comment.comment', [
        'replys' => $this->comment->replies
    ]);
}

}
`

When I call {{$model - > likers() - > count()}} on the front end, the N + 1 problem occurs.

I use ‘beyondcode/laravel-query-detector’ package to remind me:

截屏2021-09-01 下午10 52 46

and debugbar :

截屏2021-09-01 下午10 53 15

Thank you very much for providing such a powerful package, and I hope you can help me. This problem has bothered me for a week, but it still can't be solved. Thank you very much again!

cancel friend request?

Hello,
is there a method to cancel a friend request?
sometimes a visitor may click the befriend button by mistake and want to revoke it. Is this possible or should I write my own query?

[feature] Watch Later/Saved?

Thanks for providing this great package. :)

I was thinking of adding saved methods, would you accept this as a PR? A lot of websites offer this feature like FB & Reddit.
This would be very useful when exploring models (posts, books, videos, music, etc.).

If this can be done differently or you think this out of the scope of this package, just let me know.

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.