I have a table User
, which has an id
. In another table (AdminUser
), I want to reference it, but with camelCase convention.
However, Laravel doesn’t convert that and/or recognize the user table, so it returns always null
when asking for the user from the other table.
I am experimenting with something, so the table layout User
and AdminUser
might be weird, but that is not the point of the question.
Here is the AdminUser
table:
Schema::create('AdminUser', function (Blueprint $table) {
$table->id();
$table->foreign('userId');
$table->integer('pin');
$table->string('passcode');
$table->timestamp('updatedAt');
$table->timestamp('createdAt');
});
Here is the User
table:
Schema::create('User', function (Blueprint $table) {
$table->id();
$table->string('username');
$table->string('password');
$table->enum('role', ['ADMIN', 'USER'])->default('USER');
$table->string('loginToken')->nullable();
$table->rememberToken()->nullable();
$table->renameColumn('remember_token', 'rememberToken');
$table->timestamp('createdAt');
$table->timestamp('updatedAt');
});
If I reference it with user_id
in the AdminUser
table, it is working properly, but I would like to find out how to use camelCase foreign keys.
2
Answers
Solution found
All I had to do, is to add some modifications into the
foreignId
function. It looks like this now:And I also had to slightly modify the relationship as well:
It sounds like you’re looking to establish relationships between your tables in Laravel using the camel Case convention for foreign keys. Laravel does have its conventions for table and column names for good reasons. However, if you’re experimenting and want to understand how to approach this, here’s a professional perspective.
Laravel’s conventions are designed to enhance readability and maintainability across projects. When working within Laravel’s ecosystem, adhering to these conventions can simplify development and make your code more intuitive for other developers familiar with Laravel.
Still, if you want this then here is the solution:
In your migration file of AdminUser(considering that your Model name is "AdminUser") table add this for DB level relationship:
In your User model, add this for Model level relationship:
In your AdminUser model, add this for Model level relationship: