PHP code example of igaster / eloquent-inheritance

1. Go to this page and download the library: Download igaster/eloquent-inheritance 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/ */

    

igaster / eloquent-inheritance example snippets


"   "igaster/eloquent-inheritance": "~1.0"
}

// Model Foo is the parent model
Schema::create('foo', function (Blueprint $table) {
    $table->increments('id');
    $table->integer('a');
});

// Model Bar inherits Foo.
Schema::create('bar', function (Blueprint $table) {
    $table->increments('id');
    $table->integer('b');
    $table->integer('foo_id')->nullable(); // Foreign Key to Foo
});

class Foo extends Eloquent
{
    use \igaster\EloquentInheritance\EloquentInherited;

	// ...
    public function fooMethod(){}
}

class Bar extends Eloquent
{
    use \igaster\EloquentInheritance\EloquentInherited;

	// ...
    public function barMethod(){}
}

class BarExtendsFoo extends igaster\EloquentInheritance\InheritsEloquent{
    // Set Parent/Child classes
    public static $parentClass = Foo::class;
    public static $childClass  = Bar::class;

    // You must declare Parent/Child keys explicity:
    public static $parentKeys = ['id','a'];
    public static $childKeys  = ['id','b','foo_id'];

    // Childs Foreign Key (points to Parent)
    public static $childFK  = 'foo_id';

    // You can add your functions / variables ...
    public function newMethod(){}
}

// Create a composite Model:
$fooBar = BarExtendsFoo::create([ // Creates and Saves Foo & Bar in the Database
    'a' => 1,
    'b' => 2,
]);

// Access Attributes:
$fooBar->a; // = 1 (from Foo model)
$fooBar->b; // = 2 (from Bar model)

// Call Methods:
$fooBar->fooMethod(); // from Foo Model
$fooBar->barMethod(); // from Bar Model
$fooBar->newMethod(); // from self

// Query as an Eloquent model:
$fooBar = BarExtendsFoo::find(1);
$fooBar = BarExtendsFoo::where('a',1)->first();
$fooBar = BarExtendsFoo::get();     // Collection of BarExtendsFoo 

$fooBar->save();    // Saves Foo & Bar
$fooBar->delete();  // Deletes Foo & Bar
$fooBar->update([   // Updates Foo & Bar
    'a' => 10,
    'b' => 20,
]);