Eloquent has certain conventions, but they can be over-written.
May 24, 2025
5
Level 2
Explicit need for a key name
Why do I explicitly need to set the key name in relationships, even though the tables have appropriate field names. For example
class Post extends Model
{
use HasFactory;
//
public function getpostdetail() // get the post from the post_details table
{
return $this->hasOne(PostDetail::class, 'post_id', 'id');
}
}
works as expected, whereas the following fails
return $this->hasOne(PostDetail::class);
The post_details table does indeed have the post_id column. The same is true for all other relationships, for example, in a Links model I have the following relationship that works:
return $this->belongsTo(Post::class, 'post_id');
Whereas this does not:
return $this->belongsTo(Post::class);
Even though the links table has the post_id column.
Please or to participate in this conversation.