Laravel Polymorphic Relationships Issue

  laravel, laravel-8, polymorphism

I’m trying to take advantage of the Laravel’s Polymorphic Relationships

I’m building an app where I have 3 tables: products, expenses and hunts.

Each product, expense or hunt belongs to a category. I used to have 3 other different tables product_categories, expenses_categories and hunts_categories but I didn’t like doing it this way so I did a little bit of research and found about this Polimorphic Relationships thing but I’m not really sure how to use it.

I’ve create a new category table with the following columns

$table->id();
$table->string('name');
$table->integer('categorizable_id');
$table->string('categorizable_type');
$table->foreignId('icon_id')->constrained();

My models looks like

class Product extends Model
{
    public function category () {
        return $this->morphOne(Category::class, 'categorizable');
    }
}

class Expense extends Model
{
    public function category () {
        return $this->morphOne(Category::class, 'categorizable');
    }
}

class Hunt extends Model
{
    public function category () {
        return $this->morphOne(Category::class, 'categorizable');
    }
}

class Category extends Model
{
    public function icon () {
        return $this->belongsTo(Icon::class);
    }

    public function categorizable () {
        return $this->morphTo();
    }
}

I only want 5 categories for the expenses table so I’m seeding them directly to the database but products categories and hunt categories are created by the user

In my CategorySeeder.php file I have the following function

public function run()
    {
        DB::table('categories')->insert([
            ['name' => 'Advertising', 'icon_id' => 1, 'categorizable_id' => ?, 'categorizable_type' => 'AppModelsExpense'],
            ['name' => 'Utilities', 'icon_id' => 2],
            ['name' => 'Shopping', 'icon_id' => 3],
            ['name' => 'Payroll', 'icon_id' => 4],
            ['name' => 'Other', 'icon_id' => 5]
        ]);
    }

Since I want those categories before creating any expense. What should I do with categorizable_id column?

Source: Laravel

Leave a Reply