In this episode, we make the big switch from using hard-coded, manual data on our homepage to actually pulling real data from a database. The goal is to connect to a MySQL database and fetch users dynamically, so our app gets a lot closer to something you'd use in production.
We kick things off by setting up Laravel's Eloquent ORM outside of a normal Laravel project, using the standalone illuminate/database
package. We do a composer require, set up our environment variables, and create a new database service provider to centralize all the configuration. There's a bit of a walkthrough on how to configure MySQL connection details (host, database, username, password, etc.) using env vars, so you can easily switch between local and production setups.
Once the config is done, we actually create a simple users
table manually, toss in a few test users, and then wire up the database manager so that our controller can run queries. The highlight is doing a basic .get()
query to fetch all users from the database, dumping the results out to show how Eloquent collections work, and then looping through them in the Twig template. At this point, we've fully replaced static data with real database records!
The episode wraps up with a quick note: we're still directly querying the database, but next episode, we'll improve everything by moving over to proper Eloquent models for even cleaner code and better features. So, if you're following along, you now have database queries set up and ready for the next step!