PHP code example of servnx / getcandy-favorites

1. Go to this page and download the library: Download servnx/getcandy-favorites 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/ */

    

servnx / getcandy-favorites example snippets


php artisan vendor:publish --tag="getcandy-favorites"
 
php artisan migrate

/*
* If you have GetCandy Admin Hub installed set this to true (default is false).
*/
'hub' => true,

use Servnx\GetCandyFavorite\Traits\Favoriter;

class User extends Authenticatable
{
    use HasFactory,
        GetCandyUser,
        Favoriter,
        Billable,
        Notifiable;
       
    ...
}
 
GetCandy\Models\Product::class
... more to come ...
 
use Illuminate\Database\Eloquent\Model;
use Servnx\GetCandyFavorite\Traits\Favoriteable;

class Post extends Model
{
    use Favoriteable;
    
    ...
}

$user = User::find(1);
$product = Product::find(2);

$user->favorite($product);
$user->unfavorite($product);
$user->toggleFavorite($product);
$user->getFavoriteItems(Product::class)

$user->hasFavorited($product);
$product->hasBeenFavoritedBy($user);

foreach($product->favoriters as $user) {
    ...
}

$favoriteItems = $user->getFavoriteItems(Product::class);

// more examples
$favoriteItems->get();
$favoriteItems->paginate();
$favoriteItems->find(1)->get();

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

// how many Products has this user favorited ?
$user->favorites()->withType(Product::class)->count();

// how many users favorited this product ?
$product->favoriters->count();

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

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


// for Favoriteable models:
$products = Product::withCount('favoriters')->get();

foreach($products as $product) {
    echo $product->favoriters_count;
}

$product = Product::find(1);

$product = $user->attachFavoriteStatus($product);

$product->toArray();

// example result
[
    "id" => 1
    ...
    "has_favorited" => true
],

$products = Product::oldest('id')->get();

$products = $user->attachFavoriteStatus($products);

$products->toArray();

// example result
[
  [
    "id" => 1
    ...
    "has_favorited" => true
  ],
  [
    "id" => 2
    ...
    "has_favorited" => false
  ],
  [
    "id" => 3
    ...
    "has_favorited" => true
  ],
]

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

// Favoriteable
$products = Product::with('favorites')->get();
$products = Product::with('favoriters')->get();