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

FallOutBoi's avatar

Custom table name not working on many to many polymorphic relationship

Hello, i am running into a problem when i am trying to save polymorphic relationship. It says SQLSTATE[42S02]: Base table or view not found: 1146 Table 'database.audit_trails' doesn't exist . I have set up the custom name inside the model like so

//AuditTrail.php
<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use App\BirthNotification;

class AuditTrail extends Model
{
  protected $table = 'audit_trail';

  public function bn()
  {
      return $this->morphedByMany(BirthNotification::class, 'audit_trail');
  }
}

Here's the second model

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use App\AuditTrail;

class BirthNotification extends Model
{
    protected $table = "birth_notification";

    public function audit()
    {
        return $this->morphToMany(AuditTrail::class, 'audit_trail');
    }
}

But for some reason it can't find the table by that name even though it exists.I am trying to insert into the model like this.

    $bn = BirthNotification::find($id);
    $bn->ba_status_id = $statusId;
        $bn->save();

        $trail = new AuditTrail;
        $trail->user_id = Auth::user()->id;
        $trail->auditable_id = $bn->id;
        $trail->auditable_type = 'App/BirthNotification';
        $trail->description = 'Birth Notification Update Status To' . $status_name[0];
        $trail->txn_date = $date;
        $trail->txn_time = $time;
        $bn->audit()->save($trail);

I also tried to run composer dump but still it didn't worked :( What am i doing wrong?

0 likes
1 reply
Nakov's avatar

From the method signatures, the 3d parameter is the table name to the morphedByMany and morphToMany relationships..

public function morphedByMany($related, $name, $table = null, $foreignPivotKey = null,
                                  $relatedPivotKey = null, $parentKey = null, $relatedKey = null)
public function morphToMany($related, $name, $table = null, $foreignPivotKey = null,
                                $relatedPivotKey = null, $parentKey = null,
                                $relatedKey = null, $inverse = false)

Even though you are overriding the table name in the model itself, I don't know why that does not work.

1 like

Please or to participate in this conversation.