PHP code example of dive-be / eloquent-super

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

    

dive-be / eloquent-super example snippets


Schema::create('addresses', static function (Blueprint $table) {
    $table->id();
    $table->foreignId('country_id')->constrained();
    $table->morphs('addressable'); // ==> mandatory
    
    // ... other columns
});

class Address extends Model
{
    protected $fillable = ['city', 'country_id', 'street', 'postal_code'];

    public function country(): BelongsTo
    {
        return $this->belongsTo(Country::class);
    }
}

class ShippingAddress extends Model
{
    use \Dive\EloquentSuper\InheritsFromSuper;

    protected $fillable = ['email', 'phone', 'contact_person', 'is_expedited', 'courier'];
    
    protected function getSuperClass(): string
    {
        return Address::class;
    }
}

class InvoiceAddress extends Model
{
    use \Dive\EloquentSuper\InheritsFromSuper;

    protected $fillable = ['company_id', 'email', 'fax', 'phone', 'language'];
    
    protected function getSuperClass(): string
    {
        return Address::class;
    }
}

$address = ShippingAddress::create($request->validated());

$address->getAttributes(); // 'email', 'phone', 'contact_person', 'is_expedited', 'courier'
$address->super->getAttributes(); // 'city', 'country_id', 'street', 'postal_code'

$address->city; // Ghent
$address->super->city; // Ghent

$address->country; // App\Models\Country { #2981 }
$address->super->country; // App\Models\Country { #2981 }

$address->delete(); // Database transaction in the background