Laravel Collect is a collection extension I developed, borrowed from Cybercog/Laravel love, and I had the opportunity to participate in the community’s translation of this extension to add likes and hates to your Eloquent model. My original intention is to learn how to develop the Laravel extension pack, so the implementation may be relatively simple, please do not write. But it’s great for those of you who want to learn how to develop the Laravel extension. Thank you for your support.

The recent discovery that my expansion packs have been used in projects has given me more motivation to keep improving. Fight!

The installation

Install by composer using the following command:

$ composer require vetor/laravel-collect
Copy the code

We need to execute the model migration command to publish the Collections table to our database:

$ php artisan migrate
Copy the code

use

In our Collector table, the User table, we need to implement the CollectorContract interface and reference the Collector trait:

use Illuminate\Foundation\Auth\User as Authenticatable;
use Vetor\Laravel\Collect\Collector\Models\Traits\Collector;
use Vetor\Contracts\Collect\Collector\Models\Collector as CollectorContract;

class User extends Authenticatable implements CollectorContract
{
    use Collector;
}
Copy the code

To bookmark articles, implement the CollectableContract interface in the Article table and reference the Collectable trait:

use Vetor\Laravel\Collect\Collectable\Models\Traits\Collectable;
use Vetor\Contracts\Collect\Collectable\Models\Collectable as CollectableContract;

class Article extends Model implements CollectableContract
{
    use Collectable;
}
Copy the code

Available methods

For the user, the methods available are:

/ / collection$user->collect($article); // Cancel the collection$user->cancelCollect($article); // All of the user's favorites$user->collections; // User's favorite article records$user->collectionsWhereCollectable(Article::class);
Copy the code

The methods available to the article are:

/ / collection$article->collect(); // Unfavorites (default is the current user, the user instance can be passed in as an argument)$article->cancelCollect(); // Get the collection of articles$article->collections(); // Get the number of articles collected$article->collections_count; // Sort by collection number (ascending order)'asc'; Descending order'desc'; The default is ascending) Article: : orderByCollectionsCount () - > get ();Copy the code

We can get all the articles in the favorites list by:

Collection::whereCollectable(Article::class)->get();
Copy the code

More and more

Code refer to Github warehouse Vetor/laravel-Collect, welcome to put forward your own ideas, point out the shortcomings, we learn and progress together. Thanks again to Cybercog/Laravel-Love.