/vispobish

tree structure for laravel

Primary LanguagePHP

Vispobish

Add tree structure to Eloquent models. In this package try to use optimize queries.

Installing

just run below command:

composer require aminsamadzadeh/simorgh

Usage

Create migration.

...
public function up()
{
	Schema::table('categories', function (Blueprint $table) {
		// vispobish pckage
		$table->string('path')->nullable(); // save path of tree
		$table->unsignedInteger('parent_id')->nullable();
		$table->foreign('parent_id')->references('id')->on('categories');
	});
}
...

Add Treeable trait to model.

...
use Illuminate\Database\Eloquent\Model;
use AminSamadzadeh\Vispobish\Treeable;

class Category extends Model
{
    use Treeable;
}
...

Named Path

if you want save path with spicial name you can add public $namedPathWith property to your model and add named_path to migration.

...
public function up()
{
	Schema::table('categories', function (Blueprint $table) {
		$table->string('named_path')->unique(); // just used when set $pahtNamedWith
	});
}
...
...
class Category extends Model
{
    use Treeable;
    public $namedPathWith = 'name';
}
...

Relationship

  • $cat->parent() get parent
  • $cat->children() get children
  • $cat->descendants() get flatten children of childrens
  • $cat->ancestors() get flatten all parents