PHP code example of tobischulz / laravel-favoritable

1. Go to this page and download the library: Download tobischulz/laravel-favoritable 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/ */

    

tobischulz / laravel-favoritable example snippets




namespace App;

use Illuminate\Database\Eloquent\Model;
use TobiSchulz\Favoritable\Traits\Favoriteable;

class Post extends Model
{
    use Favoriteable;

    // ...
}



namespace App;

use Illuminate\Foundation\Auth\User as Authenticatable;
use TobiSchulz\Favoritable\Traits\HasFavorites;

class User extends Authenticatable
{
    use HasFavorites;

    // ...
}



/**
 * API for Favoritable
 */
$post = Post::find(1);

$post->addFavorite();   // adds this post to favorites to current user
$post->removeFavorite();    // remove this post from favorites
$post->toggleFavorite();    // toggle this post as favorite
$post->isFavorited();   // returns boolean for this post favorite state


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

$post->addFavorite($user);  // adds favorite for this post and a specific user.

/**
 * API for HasFavorites
 */
$user = User::find(1);

$user->favorites(Post::class);  // returns collection of Post::class favorites

bash
php artisan vendor:publish --provider=TobiSchulz\Favoritable\FavoritableServiceProvider
bash
php artisan migrate