In this episode, we focus on getting our messages saved to the database. We start by creating a Message
model and the corresponding database migration. This includes foreign key relationships so every message knows which room it was sent in and which user sent it. Of course, we also add the actual message body where the text lives.
Once that's set up, we run our migration to create the table. We then jump into the Message
model and set up basic relationships, so each message knows which user and which room it belongs to. We talk a bit about model mass assignment, fillable fields, and guarding the right properties.
After setting up the relationships, we implement the backend logic to handle storing new messages. This includes validating the message body to make sure it's not empty and then creating the new message, associating it with the current user and room. We make sure to persist everything to the database and reset the input for a good user experience.
We also tweak the handling of the message input so hitting Enter submits the message, while Shift+Enter lets you add a new line. Finally, we take a look in the database and confirm that messages are being stored with their user and room references — success!
Up next, we'll work on displaying these messages on the page and making sure they show up immediately when a user sends one.