PHP code example of orlyapps / laravel-favorite

1. Go to this page and download the library: Download orlyapps/laravel-favorite library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

orlyapps / laravel-favorite example snippets


$ php artisan vendor:publish --provider="Overtrue\\LaravelFavorite\\FavoriteServiceProvider" --tag=config

$ php artisan vendor:publish --provider="Overtrue\\LaravelFavorite\\FavoriteServiceProvider" --tag=migrations


use Illuminate\Notifications\Notifiable;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Overtrue\LaravelFavorite\Traits\Favoriter;

class User extends Authenticatable
{
    use Favoriter;
    
    <...>
}

use Illuminate\Database\Eloquent\Model;
use Overtrue\LaravelFavorite\Traits\Favoriteable;

class Post extends Model
{
    use Favoriteable;

    <...>
}

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

$user->favorite($post);
$user->unfavorite($post);
$user->toggleFavorite($post);
$user->getFavoriteItems(Post::class)

$user->hasFavorited($post); 
$post->isFavoritedBy($user); 

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

$user->getFavoriteItems(Post::class);

// Do more
$favortePosts = $user->getFavoriteItems(Post::class)->get();
$favortePosts = $user->getFavoriteItems(Post::class)->paginate();
$favortePosts = $user->getFavoriteItems(Post::class)->where('title', 'Laravel-Favorite')->get();

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

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

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

$users = User::withCount('favorites')->get();

foreach($users as $user) {
    echo $user->favorites_count;
}

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

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

// Favoriteable
$posts = App\Post::with('favorites')->get();
// or 
$posts = App\Post::with('favoriters')->get();

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