In this episode, we're setting up the groundwork for user notification preferences! We start by figuring out how we’ll store each user’s preferences for various notification channels (like email or Slack) on a per-notification type basis.
We dive into creating a new pivot table, notification_user
, which connects users to notification types along with their selected channels. To keep things flexible and simple, we use a JSON column for channels so a user can easily opt in or out of different ways to be notified.
After setting up the migration, we walk through adding the correct relationship to the User model—just remember not to name it notifications
as that could mess with Laravel’s built-in stuff. Instead, we go with notificationPreferences
, making it nice and clear.
The episode also covers creating a custom pivot model so we can automatically cast the channels from JSON to an array when accessing them in PHP. This keeps our code clean and means we don’t have to manually decode things.
Finally, we test out the relationship by manually inserting a preference in the database and then retrieving it to make sure our setup works, showing how the channels come back as a proper array. Next time, we'll hook this all up with tests and eventually wire it up to a notification form for real users to save their preferences!