Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Lars-Janssen's avatar

Morph to relation

Hello,

I've got 3 tables for subscribing to a topic.

Topic
User
Subscription

Subscriptions looks like this:

  Schema::create('subscription', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('user_id')->index();
            $table->integer('subscription_id');
            $table->string('subscription_type');
            $table->timestamps();

            $table->unique(['user_id', 'subscription_id', 'subscription_type']);
        });

My relation in the ``Topic``` model:

public function subscriptions()
{
    return $this->morphMany(Subscription::class, 'subscription');
}

So I successfully receive topics that a user has subscribed. But how do I store them?

When I try this in tinker:

 App\Square\Topics\Topic::first()->subscriptions()->save(App\Square\Users\User::first());

I receive:

Illuminate\Database\QueryException with message 'SQLSTATE[42S22]: Column not found: 1054 Unknown column 'subscription_type' in 'field list' (SQL: update `user` set `updated_at` = 2016-10-03 06:52:08, `subscription_type` = App\Square\Topics\Topic, `subscription_id` = 1 where `id` = 1)'

What am I doing wrong here?

0 likes
0 replies

Please or to participate in this conversation.