Git Product home page Git Product logo

laravel-like's Introduction

Laravel Like

👍 User-like features for Laravel Application.

CI

Sponsor me

Installing

composer require overtrue/laravel-like -vvv

Configuration and Migrations

php artisan vendor:publish --provider="Overtrue\LaravelLike\LikeServiceProvider"

Usage

Traits

Overtrue\LaravelLike\Traits\Liker

use Illuminate\Notifications\Notifiable;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Overtrue\LaravelLike\Traits\Liker;

class User extends Authenticatable
{
    use Liker;

    <...>
}

Overtrue\LaravelLike\Traits\Likeable

use Illuminate\Database\Eloquent\Model;
use Overtrue\LaravelLike\Traits\Likeable;

class Post extends Model
{
    use Likeable;

    <...>
}

API

$user = User::find(1);
$post = Post::find(2);

$user->like($post);
$user->unlike($post);
$user->toggleLike($post);

$user->hasLiked($post);
$post->isLikedBy($user);

Get user likes with pagination:

$likes = $user->likes()->with('likeable')->paginate(20);

foreach ($likes as $like) {
    $like->likeable; // App\Post instance
}

Get object likers:

foreach($post->likers as $user) {
    // echo $user->name;
}

with pagination:

$likers = $post->likers()->paginate(20);

foreach($likers as $user) {
    // echo $user->name;
}

Aggregations

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

// short way
$user->totalLikes;

// with type
$user->likes()->withType(Post::class)->count();

// likers count
$post->likers()->count();

// short way
$post->totalLikers

List with *_count attribute:

// likes_count
$users = User::withCount('likes')->get();

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

// likers_count
$posts = User::withCount('likers')->get();

foreach($posts as $post) {
    // $post->likes_count;
}

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:

// Liker
$users = App\User::with('likes')->get();

foreach($users as $user) {
    $user->hasLiked($post);
}

// Likeable
$posts = App\Post::with('likes')->get();
// or
$posts = App\Post::with('likers')->get();

foreach($posts as $post) {
    $post->isLikedBy($user);
}

Of course we have a better solution, which can be found in the following section:

Attach user like status to likeable collection

You can use Liker::attachLikeStatus($likeables) to attach the user like status, it will attach has_liked attribute to each model of $likeables:

For model

$post = Post::find(1);

$post = $user->attachLikeStatus($post);

// result
[
    "id" => 1
    "title" => "Add socialite login support."
    "created_at" => "2021-05-20T03:26:16.000000Z"
    "updated_at" => "2021-05-20T03:26:16.000000Z"
    "has_liked" => true
 ],

For Collection | Paginator | LengthAwarePaginator | array:

$posts = Post::oldest('id')->get();

$posts = $user->attachLikeStatus($posts);

$posts = $posts->toArray();

// result
[
  [
    "id" => 1
    "title" => "Post title1"
    "created_at" => "2021-05-20T03:26:16.000000Z"
    "updated_at" => "2021-05-20T03:26:16.000000Z"
    "has_liked" => true
  ],
  [
    "id" => 2
    "title" => "Post title2"
    "created_at" => "2021-05-20T03:26:16.000000Z"
    "updated_at" => "2021-05-20T03:26:16.000000Z"
    "has_liked" => fasle
  ],
  [
    "id" => 3
    "title" => "Post title3"
    "created_at" => "2021-05-20T03:26:16.000000Z"
    "updated_at" => "2021-05-20T03:26:16.000000Z"
    "has_liked" => true
  ],
]

For pagination

$posts = Post::paginate(20);

$user->attachLikeStatus($posts);

Events

Event Description
Overtrue\LaravelLike\Events\Liked Triggered when the relationship is created.
Overtrue\LaravelLike\Events\Unliked Triggered when the relationship is deleted.

Related packages

❤️ 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

laravel-like's People

Contributors

dependabot-preview[bot] avatar dependabot-support avatar dependabot[bot] avatar git-zjx avatar hafidd4 avatar hy7716 avatar jonasva avatar koossaayy avatar lahirulhr avatar laravel-shift avatar livijn avatar luckcolors avatar michavie avatar mingyoung avatar natecorkish avatar overtrue avatar puzzle9 avatar summerblue avatar zhouzishu 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

laravel-like's Issues

How to get user all posts total like?

If user has 5 posts and each post has 5 likes, so there should be all posts total likes = 25.
I think it should like this

$user()->totalLikes()->count()

Likes relationship

I would recommend to add likes relationship:

public function likes(): \Illuminate\Database\Eloquent\Relations\MorphMany
{
    return $this->morphMany(config('like.like_model'), 'likeable');
}

In the same way as you did in Favorites. It is useful for delete all linked likes to the object, etc.

Likes Count Issue

After upgrading the package from 2.0 to 4.0, the following error displayed in the post index view:

Screen Shot 2021-02-25 at 8 03 21 PM

Querying the posts via Laravel as follows:

$posts = Post::withCount('likes')
            ->whereIn('user_id', function ($query) {
                $query->select('following_id')
                    ->from('user_follower')
                    ->where('follower_id', auth()->id());
            })->orWhere('user_id', auth()->id())
            ->latest()
            ->paginate(10);

Created like button as a Vue component to display the count and update it when a post is liked or unliked.

The count from the Post model is fetched via "likes_count" attribute.

Issue appears to be a bug in the package.

Separate Follow package

Just love you for your open source effort!

Can you please also create a separate Follow package without relation type column?

It will be more scalable for millions of users.

Thanks again.

like posts by company instead of user

hello
In my app the user has a company profile in addition to the his profile ( like Facebook pages).
I need to like a Post by this company profile using company_id for example.
How to implement that with your package please ?
thanks

composer install is not getting all the files.

May be it's not a issue but i was using your laravel follow unfollow package and it's working fine but when i try to install the like package and try to publish the configuration and the migration it says that the file is not found and when i try to create the like it always throws an exception saying => Class name must be a valid object or a string <= but the both models are configured as the instruction given also the post and the user are both objects when i check dd it.

Empty likers() collection

// likers count
$post->likers;

The likers count always returning empty collection!

However overwriting writing the relation method like this works fine:

public function likers()
    {
        return $this->morphToMany(User::class, 'likable', 'likes');
    }

It is working well in laravel-follow used branch. Please help!

BadMethodCallException

"message": "Call to undefined method Illuminate\Database\Eloquent\Builder::like()",
"exception": "BadMethodCallException",
......

Post Controller:
public function likePost($id)
{
$user = User::where('id', auth()->user()->id);
$post = Post::find($id);

    $user->like($post);

    return response(['message' => 'Post Like successfully!']);
}

Post Model:

Support for laravel cursor paginate?

I attempted to use this packages attachLikeStatus on a cursorPaginated eloquent model. Which doesn't seem to work. With normal pagination it works fine.

$listings = Listing::filterByRequest($request)
                       ->cursorPaginate($perPage);

$currentUser = Auth::user();
if (Auth::check()) {
    $listings = $currentUser->attachLikeStatus($listings);
}

I added a CursorPaginator handler to Liker.php trait and now the above works:

case $likeables instanceof CursorPaginator:
    $likeables = \collect($likeables->items());
    break;

某个用户 like 的数据、分页获取,可否获取文章的用户信息?

单独获取 某篇文章,这样是可以获取到用户信息的

$likers = $post->likers()->paginate(20);

foreach($likers as $user) {
    // echo $user->name;
}

但是我如果 Get user likes with pagination:

$likes = $user->likes()->with('likable')->paginate(20);

foreach ($likes as $like) {
    $like->likable; // App\Post instance
}

这种方式好像没有办法获取用户的详细信息,超哥是否有其他的方法?

How to get user Like on post collection?

$posts = Post::with('post_images')->with('user')->withCount('comments')->orderBy('created_at', 'desc')->get();

how to get total likes for each post?

thank you

Composer wont install because of vulnerabilities

Composer fails installing, audit throws this message:

+-------------------+----------------------------------------------------------------------------------+
| Package           | guzzlehttp/guzzle                                                                |
| CVE               | CVE-2022-31091                                                                   |
| Title             | Change in port should be considered a change in origin                           |
| URL               | https://github.com/guzzle/guzzle/security/advisories/GHSA-q559-8m2m-g699         |
| Affected versions | >=7,<7.4.5|>=4,<6.5.8                                                            |
| Reported at       | 2022-06-20T22:24:00+00:00                                                        |
+-------------------+----------------------------------------------------------------------------------+
+-------------------+----------------------------------------------------------------------------------+
| Package           | guzzlehttp/guzzle                                                                |
| CVE               | CVE-2022-31090                                                                   |
| Title             | CURLOPT_HTTPAUTH option not cleared on change of origin                          |
| URL               | https://github.com/guzzle/guzzle/security/advisories/GHSA-25mq-v84q-4j7r         |
| Affected versions | >=7,<7.4.5|>=4,<6.5.8                                                            |
| Reported at       | 2022-06-20T22:24:00+00:00                                                        |

Error Publishing Migrations and Config

This package doesn't seem to create or publish migrations in my Laravel 9 installation.

The command php artisan vendor:publish --provider="Overtrue\\LaravelLike\\LikeServiceProvider" --tag=migrations throws a warning: No publishable resources for tag [migrations].

The warning is the same for --tag=configs as well.

Also, I might be wrong, but the package doesn't create a default likes table migration which I can use. Do I have to manually create a likes table or is the package supposed to create a default migration for me?

Like and Unlike Event not dispatching!

Please note that I extended the package traits CanLiked, CanBeLiked in my App/Libraries/Like namespace. Then used the extended traits in the target models. Thanks

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.