PHP code example of ehsanmoradi / categorizable
1. Go to this page and download the library: Download ehsanmoradi/categorizable 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/ */
ehsanmoradi / categorizable example snippets
'providers' => [
...
\EhsanMoradi\Categorizable\CategorizableServiceProvider::class,
],
namespace App;
use Illuminate\Database\Eloquent\Model;
use EhsanMoradi\Categorizable\Categorizable;
class Post extends Model
{
use Categorizable;
}
use App\Post;
use EhsanMoradi\Categorizable\Category;
// first we create a bunch of categories
// create "BackEnd" category
Category::create([
'name' => 'BackEnd'
]);
// create "PHP" category
Category::create([
'name' => 'PHP'
]);
// create "FrontEnd" category
Category::create([
'name' => 'FrontEnd'
]);
// create "Test" Category (alternative way)
$test = new Category();
$test->name = 'Test';
$test->save();
// assign "PHP" as a child of "BackEnd" category
$parent = Category::findByName('BackEnd');
$child = Category::findByName('PHP');
$parent->appendNode($child);
// delete "Test" Category
$testObj = Category::findByName('Test');
$testObj->delete();
// assuming that we have these variables
$post = Post::first();
// 3 different ways of getting a category's instance
$backendCategory = Category::findById(1); // 'BackEnd'
$phpCategory = Category::findByName('PHP'); // 'PHP'
$frontendCategory = Category::find(3); // 'FrontEnd'
$post->attachCategory($phpCategory);
$post->detachCategory($phpCategory);
$post->syncCategories([
$phpCategory,
$backendCategory
]);
$post->syncCategories([]);
$post->syncCategories([
$frontendCategory
]);
// removes attached categories & adds the given categories
// single use case
$post->hasCategory($phpCategory);
// multiple use case
$post->hasCategory([
$phpCategory,
$backendCategory
]);
// return boolean
$post->categoriesList();
// return array [id => name]
$post->categoriesId();
// return array
$categoryPosts = Category::find(1)
->entries(Post::class)
->get();
// return collection
$postWithCategories = Post::with('categories')
->get();
// you have access to categories() relationship in case you need eager loading
$category = Post::first()->categories()->first();
$category->parent;
// return the category's parent if available
$category = Post::first()->categories()->first();
$category->children;
// return the category's children if any
$category = Post::first()->categories()->first();
$category->ancestors;
// return the category's ancestors if any
$category = Post::first()->categories()->first();
$category->descendants;
// return the category's descendants if any
bash
php artisan vendor:publish --provider="EhsanMoradi\Categorizable\CategorizableServiceProvider"
php artisan migrate