Giter Site home page Giter Site logo

renoki-co / befriended Goto Github PK

View Code? Open in Web Editor NEW
761.0 18.0 54.0 192 KB

Eloquent Befriended brings social media-like features like following, blocking and filtering content based on following or blocked models.

License: Apache License 2.0

PHP 100.00%
laravel social media eloquent model follow following block blocking blocker

befriended's People

Contributors

clayboy avatar dependabot-preview[bot] avatar dependabot[bot] avatar hirbod avatar josezenem avatar joveice avatar laravel-shift avatar lukadriel7 avatar pkboom avatar rennokki avatar rez1dent3 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

befriended's Issues

Compatibility with Laravel UUIDs

Hi,

i'm using UUID instead of incrementing ids. I followed this tutorial to implement that mechanism: https://medium.com/@steveazz/setting-up-uuids-in-laravel-5-552412db2088 and keep getting an error while trying to follow someone.

The error message is
"message": "SQLSTATE[HY000]: General error: 1364 Field 'id' doesn't have a default value (SQL: insert intofollowers (created_at, followable_id, followable_type, follower_id, follower_type, updated_at) values (2019-03-02 10:14:16, 35863b00-2254-11e9-93a9-cf58a7333282, App\\User, d70d84e0-3863-11e9-8d2a-99a5f86ac3ee, App\\User, 2019-03-02 10:14:16))",

I just inserted my trait to "auto generate uuid" when creating new rows and updated my migratons and models.

Anyone have an advice how I can implement support for UUIDs?

Best regards

[bug] Can't follow models with MorphMap

Probably linked with #47 but I wanted to create a new issue with the current code

When using morphMap, Laravel will not use the fully qualified class name, which breaks the current implementation of getModelMorphClass.

for example using 'user' => 'App\Models\User' starting from isFollowing

  /**
   * Check if the current model is following another model.
   *
   * @param  \Illuminate\Database\Eloquent\Model  $model
   * @return bool
   */
  public function isFollowing($model): bool
  {
      if (! $model instanceof Followable && ! $model instanceof Following) {
          return false;
      }

      return ! is_null(
          $this
              ->following((new $model)->getMorphClass()) // will be 'user'
              ->find($model->getKey())
      );
  }

Now in following

    /**
     * Relationship for models that this model is currently following.
     *
     * @param  null|\Illuminate\Database\Eloquent\Model  $model
     * @return mixed
     */
    public function following($model = null)
    {
        // $model === 'user'
        $modelClass = $this->getModelMorphClass($model);

        return $this
            ->morphToMany($modelClass, 'follower', 'followers', 'follower_id', 'followable_id')
            ->withPivot(['followable_type', 'accepted'])
            ->wherePivot('followable_type', $modelClass)
            ->wherePivot('follower_type', $this->getMorphClass())
            ->wherePivot('accepted', true)
            ->withTimestamps();
    }

and finally, in getModelMorphClass

    /**
     * Get the model's morph class to act as the main resource.
     *
     * @param  string|null  $model
     * @return string
     */
    protected function getModelMorphClass($model = null)
    {
        return $model
            // FIXME: $model is still 'user' and Not 'App\Models\User' which causes exception
            ? (new $model)->getMorphClass()
            : $this->getCurrentModelMorphClass();
    }

Screen Shot 2021-04-17 at 7 27 40 PM

Hope this helps

Comments?

How about adding threaded comments

Cannot follow a Model

Hello, I've tried to implement a feature were the user is able to follow a page. But the problem is that the page is not getting followed. Let me show you my code:

Company.php (the model):

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use Rennokki\Befriended\Traits\Follow;
use Rennokki\Befriended\Contracts\Following;
use Rennokki\Befriended\Scopes\FollowFilterable;
use Rennokki\Befriended\Traits\CanBeFollowed;
use Rennokki\Befriended\Contracts\Followable;
use Spatie\MediaLibrary\HasMedia\HasMedia;
use Spatie\MediaLibrary\HasMedia\HasMediaTrait;

class Company extends Model implements Following, HasMedia
{
    use HasMediaTrait, Follow, FollowFilterable;

    protected $table = "companies";

    protected $fillable = [

        'name',
        'user_id',
        'website',
        'company_id',
        'numberofemployees',
        'ishiring',
        'verified',
        'identifier'

    ];

Controller:

public function followcomp($identifier){
        $identifier = Company::where('identifier', $identifier)->first();
        $user = Auth::user();
        $user->follow($identifier);
        return redirect::back();
    }

    public function unfollowcomp($identifier){
        $identifier = Company::where('identifier', $identifier)->first();
        $user = Auth::user();
        $user->unfollow($identifier);
        return redirect::back();
    }

What am I actually doing wrong?

Thanks in advance!

Most liked posts?

How would I go about getting the most liked posts? I've tried a few different queries but couldn't get anything working correctly. Thanks in advance for any help!

How to delete all likes related to a post when deleting post?

Thank you for your good package, it works great.
I want to delete the related likes when deleting a post. How is this possible?
I use this method in the model but it does not work!

 protected static function boot()
    {
        parent::boot();
        static::deleting(function($model) {
            $model->likers()->delete();
        });
    }

follow a `Followable` model always return false

Hi,

Maybe I've missed something when using this package :

I have a Follower User model and another Followable model

when I run the $user->follow($myModel) I always get a false return.
I saw the preliminary check in follow($model) methods don't checks the Followable implementation. Is it normal?

Am I doing something the wrong way?

Thanks & good job for this usefull package

How can i retrieve a followed user's posts?

I've tried with this:

$posts = Post::with('comments')->latest()->get();
$user->following($posts)->get();

But it is not working for me, how can i properly do it?
I've tried other options such as:

$user->following()->load('posts');
$user->following()->get()->load('posts');
$user->following()->with('posts');

Thanks in advance for the help.

P.D:
I'm trying to retrieve the posts that have the comment relationship on them as you can see:

$posts = Post::with('comments')->latest()->get();

Likeable contract problem

the likeable contract for models return always false when checking
if (! $model instanceof Likeable && ! $model instanceof Liking)
in CanLike.php isLiking() function.

Vendor Publish Errors

Hello, I tried php artisan vendor:publish and I got an error like:

Can't locate path: </Users/agus/Sites/careerkuweb/vendor/rennokki/befriended/src/../database/migrations/2018_07_14_183253_followers.php>

It's supposed to be _followers.php not _befriended.php in src/database/migrations folder.

Change README:
From use Rennokki\Befriended\Traits\Following as FollowingTrait;
To use Rennokki\Befriended\Traits\Follow as FollowingTrait;

[Feature Request] Could you add upvote/downvote features?

Hi,

Thanks for awsome package.

I found your package useful. It will be more useful and maybe will get more uses if it has upvote/downvote features.

It will be redundant if I write a new package myself because the codebase is similar to current features (Like/Follow,...).

So, could you add upvote/downvote features to this package?

Thank you,

Khanh

Support for Laravel 10

Hello,

Is there any ETA for this package to support Laravel 10?

Many apps are relying on this and it would be great to bump the version support!

Thanks

new release and documentation correction

Hello, thank you for the great package. I recently added befriended through composer and realized that following didn't work. I checked on the github page and saw that it was an issue that was corrected. I had to manually replace the file to make it work. Since it is a breaking error, maybe a release could help others not search for a long time. Also the documentation features errors in the block and like section. Instead of $user->liking() or $user->blocking() it is written $user->likings() and $user->blockings() which are misleading (I guess a typo mistake).
Again thank you very much for all

how to fetch my pending request?

hello,

Can you please help me?

$user->followerRequests()->count() (this method) gave me my pending requests count. but I need a whole pending request with the user details, can here available for methods that will give Pending requests not pending request count?

Thanks in Advance!!!

Follow Request accept on the wrong side?

It seems to me, that the order in which the models can accept a request has been reversed.
This issue is mostly to see whether I'm wrong in this or not...

// Grabbing the requests towards the currently authenticated user:
$requests = Auth::user()->followRequests()->get();

// ..

// getting the user that requested, irrelevant
$user = User::findOrFail($a_request->id); 

// what I expected to work:
// Auth::user()->acceptFollowRequest($user);

// what actually worked:
$user->acceptFollowRequest(Auth::user());

My User model is set-up to be able to follow & be followed

use Rennokki\Befriended\Traits\Follow;
use Rennokki\Befriended\Contracts\Following;

class User extends Authenticatable implements MustVerifyEmail, Following
{
    use Follow;

Optimize the queries with eager loading

So I have the following code

PostResource.php

public function toArray($request)
 {
       return [
         'author' => new UserResource($this->author),
            'likesCount' => $this->likes_count,
            'isLiked' => $this->is_liked,
           'commentsCount' => $this->comments_count,
           'text' => $this->text,
           'created_at' => $this->created_at,
            'updated_at' => $this->updated_at,
            'id' => $this->id,
       ];
   ` }

UserResource.php

return [ 
            'id' => $this->id,
            'first_name' => $this->first_name,
            'last_name' => $this->last_name,
            'username' => $this->username,
            'gender' => $this->gender,
            'birthday' => $this->birthday,
            'email' => $this->email,
            'email_verified' => !!$this->email_verified_at,
            'isFollowMe' => $this->isFollowing($authUser),
            'isFollowedByMe' => $authUser->isFollowing($this->resource),
            'isBlockedByMe' => $authUser->isBlocking($this->resource),
            'followersCount' => $this->followers_count,
            'followingCount' => $this->following_count
        ];

PostController.php

public function index()
    {
        $user = Auth::user();
        $followersPost = Post
            ::with(['author' => function ($query) {
                $query->withCount('followers', 'following');
            }])->withCount('comments', 'likes')
            ->whereHas('author', function ($query) use ($user) {
                $query->followedBy($user);
            })
            ->orWhere('author_id', $user->id)
            ->latest()
            ->paginate(7);
        return PostResource::collection($followersPost);
    }

Is there a method to optimize the queries? I mean it does 18 queries just for 3 posts ;( . I tried to search on google but find nothing

Getting a count for number of likers of a liked "Entry"

Hi,

Thank you for your Work.

I have a Entry Model and a Profile Model.

Profiles can like Comments and Entry (entries) ...

Now i want to get the informations, how many likes has the Entry with the # 193.

I tried all kind of Kombinations of the like/likers/liking ways, and i always got 0.

What is the right way ?

grafik

Allow for MorphMap relationships inside traits

Hi,

It seems as though MorphMap relationships are not handled in the following methods on traits. I extended them in my own project, but I don't have time to be making pull requests. Here is the suggested fix (this could be simplified I am sure):

public function following($model = null)
        {
             $class = $model ?: $this->getMorphClass();
             $relation =  Relation::getMorphedModel($class);
            // Account for standard classes being passed in
            if (!isset($relation) && isset($model)){
                $relation = $class;
                $class = (new $model())->getMorphClass();
            }
            return $this->morphToMany($relation ?: $class , 'follower', 'followers', 'follower_id', 'followable_id')
                ->withPivot('followable_type')
                ->wherePivot('followable_type', $class)
                ->wherePivot('follower_type', $this->getMorphClass())
                ->withTimestamps();
        }

More than anything, just wanted to let you know.

using filterFollowingsOf, retrieve the requester data

Hi there, How can I retrieve the requester data?
This is my code.

      $user = $request->user();
        $followersPost = UserPost::with(['user' => function ($query) use ($user) {
            $query->filterFollowingsOf($user);
        }])->latest()->get();
        return $followersPost;

I get all my friends data but the requester data is null?

Unable to locate publishable resources

Hi there, thanks a lot for this package.
I am having a problem installing the package.

I did
composer require rennokki/befriended
and
php artisan vendor:publish --provider="RenokiCo\Befriended\BefriendedServiceProvider" --tag="config"
and
php artisan vendor:publish --provider="RenokiCo\Befriended\BefriendedServiceProvider" --tag="migrations"

But I got

Unable to locate publishable resources.
Publishing complete.

in both vendor publish command!

My versions:

  "require": {
        "php": "^7.2.5",
        "fideloper/proxy": "^4.2",
        "fruitcake/laravel-cors": "^2.0",
        "guzzlehttp/guzzle": "^6.3",
        "intervention/image": "^2.5",
        "laravel/framework": "^7.0",
        "laravel/sanctum": "^2.4",
        "laravel/tinker": "^2.0",
        "rennokki/befriended": "^3.4"
    },

I also did
php artisan clear-compiled
and
composer dumpautoload
and
php artisan config:clear

But I get the same.

Thank you.

Filter Followers And Following

Hi @rennokki Thank You For Such Great ๐Ÿ“ฆ ๐Ÿค™ ,

I Want Filter The Follower So That I Can Notify The People Who Followed Me,
For Instance.
I'm Hamza, I Have 499 Followers, And I Want To Notify Those 499 Followers When I Just Published A Post.

I Tried To Filter Via filterFollowingsOf And followedBy, But It's Returning The Followings Watch Is Nice But, Not The Followers In My Case I Need The Opposite .

thank you ๐Ÿ’ฏ

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.