In Laravel, storing values to a join table without defining Eloquent relationship

- 1 answer

Ad

As part of the onboarding process for my Laravel app, a user can enter the ages of his or her children. A user can have many children, and so there needs to be a kids table that stores id, user_id (which references id on the users table), and kid_age. This seems like a basic one-to-many relationship—a user can have many children.

In a profile view elsewhere in the app, I have display back the ages of each child. However, that's the only point in the app where the kids make an appearance. It seems like overkill to create an entire kid model just to manage the parent to child relationship.

Is there a lighter-weight way to assign values to a join table? If so, how would I save data to that table without defining the relationship between two models?

Ad

Answer

Ad

Without using a model, you'd have to manage the tables manually in the database. I think it is far and away easier to use a model for this, so that you can create, update, delete, and sync kid models effortlessly using Laravel functions. Because you've followed the proper naming conventions for tables and ID columns, it should only take a couple of lines of code to create the new model. Seems light-weight enough to me.

Sorry for not providing another solution, but my take is go with the Laravel solution.

Ad
source: stackoverflow.com
Ad