Skip to main content

Extending Core Models

You can extend core models by creating your own classes to add custom behavior and relationships.

Model Classes

It is recommended to extend the existing model classes in Unleash Commerce rather than creating entirely new models. This allows you to inherit all the built-in functionality while adding your own customizations. Create your own model that extends a core model:
namespace App\Models;

use Esign\UnleashCommerce\Core\Models\Product as BaseProduct;
use Illuminate\Database\Eloquent\Relations\HasMany;

class Product extends BaseProduct
{
    public function reviews(): HasMany
    {
        return $this->hasMany(ProductReview::class);
    }
}

Registering Custom Models

Register your custom model using the ModelManifest in a service provider:
<?php

namespace App\Providers;

use App\Models\Product;
use Esign\UnleashCommerce\Core\Contracts\Models\Product as ProductContract;
use Esign\UnleashCommerce\Core\Facades\ModelManifest;
use Illuminate\Support\ServiceProvider;

class UnleashCommerceServiceProvider extends ServiceProvider
{
    public function register(): void
    {
        $this->registerModels();
    }

    protected function registerModels(): void
    {
        ModelManifest::replace(ProductContract::class, Product::class);
    }
}

Adding a custom factory

If you want your extended model to use a custom Laravel factory, define the factory class and override newFactory() on the model. Example model:
namespace App\Models;

use Database\Factories\ProductFactory;
use Esign\UnleashCommerce\Core\Models\Product as BaseProduct;

class Product extends BaseProduct
{
    protected static function newFactory(): ProductFactory
    {
        return ProductFactory::new();
    }
}
Example factory:
namespace Database\Factories;

use App\Models\Product;
use Illuminate\Database\Eloquent\Factories\Factory;

class ProductFactory extends Factory
{
    protected $model = Product::class;

    public function definition(): array
    {
        return [
            'name' => $this->faker->words(3, true),
            'slug' => $this->faker->unique()->slug(),
            'description' => $this->faker->paragraph(),
        ];
    }
}

Available Models to Extend

Refer to the Models Reference for a complete list of available models you can extend.