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

cjholowatyj's avatar

Laravel appears to ignore $table = 'tables' in constraint?

I have an Authors eloquent model, which points to the users table via protected $table = 'users', but when adding ->constrained()->cascadeOnDelete(), laravel appears to ignore the $table attribute on the model and instead looks for an authors table which doesn't exist!

My author_brands pivot table migration:

public function up(): void {
    if(!Schema::hasTable('author_brands')) {
        Schema::create('author_brands', static function (Blueprint $table) {
            $table->foreignIdFor(User::class, 'author_id')->constrained()->cascadeOnDelete();
            $table->foreignIdFor(Brand::class, 'brand_id')->constrained()->cascadeOnDelete();
            Database::addResourceTimestamps($table);
            $table->primary(['author_id','brand_id']);
        });
    }
}

... produces the following error ...

 SQLSTATE[HY000]: General error: 1824 Failed to open the referenced table 'authors' (Connection: mysql, SQL: alter table `author_brands` add constraint `author_brands_author_id_foreign` foreign key (`author_id`) references `authors` (`id`) on delete cascade)

How do I get laravel to use the $table property as intended?

0 likes
7 replies
rodrigo.pedra's avatar

Currently, you can use the table as the first parameter of the ->constrained() method:

$table->foreignIdFor(User::class, 'author_id')->constrained('users')->cascadeOnDelete();

You can try sending a PR to fix that behavior

Tray2's avatar

This should probably be user_id

//$table->foreignIdFor(User::class, 'author_id')->constrained()->cascadeOnDelete();

$table->foreignIdFor(User::class, 'user_id')->constrained()->cascadeOnDelete();

However, I would not use the users table for anything else than authentication, and keep all other information in an authors table. Are all the users authors?

cjholowatyj's avatar

@Tray2 Not all users are authors, which i why there's a pivot table to begin with... Also brands are connected to users by way of not being an author as well (i.e. by a created_by field)... also, users can potentially be authors for multiple brands... the Author model extends the User model, much like other models do in my project (ex. I have an Admin model, which extends the User model, and not all users are admins, but they are stored in the same table)

Tray2's avatar

@cjholowatyj Sounds like a really bad design in my opinion, the users table should only be used for authentication. You probably have a table with authors, which has a foreign key user_id, and then same for brands, the admin is a role so you should keep that in a roles table.

Please or to participate in this conversation.