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

jonnybarnes's avatar

[L5] Something is modifying my Eloquent query

I have a model User.php using table users. I also have a model XMLFeed.php using table xmlfeeds. Each model has a method called xmlfeeds() which defines a belongsToMany() method referencing the other model. In my migrations I set up a user_xmlfeed pivot table which references the relevant ids from the model’s tables. Now with data in each model’s tables if I try to run the he `atta method I get the following output:

>>> $user->xmlfeeds()->attach($feed->id);
Illuminate\Database\QueryException with message 'SQLSTATE[42P01]: Undefined table: 7 ERROR:  relation "user_x_m_l_feed" does not exist
LINE 1: insert into "user_x_m_l_feed" ("user_id", "x_m_l_feed_id") v...
                    ^ (SQL: insert into "user_x_m_l_feed" ("user_id", "x_m_l_feed_id") values (2, 381b5a02-d26b-4308-bb8f-0ab515e7cd4b))'

Why is user_xmlfeed being turned into user_x_m_l_feed?

edit: if not immediately obvious I’m using uuids for the xmlfeeds model, and for some reason laracasts doesn’t like the word attach.

0 likes
5 replies
bestmomo's avatar

Laravel generates the pivot table name with a convention : Camel case becomes snake case. So as you have XMLFeed you get x_m_l_feed.

1 like
JarekTkaczyk's avatar
Level 53

@jonnybarnes Define the table and the keys in your relation:

// User model
public function feeds()
{
  return $this->belongsToMany('XMLFeed', 'user_xmlfeed', 'user_id', 'xmlfeed_id'); // adjust namespace if needed
}

The same goes for the other model, only the keys are swapped:

// XMLFeed model
public function users()
{
  return $this->belongsToMany('User', 'user_xmlfeed', 'xmlfeed_id', 'user_id'); 
  // again, adjust namespace if needed. You can ommit user_id in this case
}
1 like

Please or to participate in this conversation.