High Level Design of an MVC Web Application: Using Models to Interact With a Database

This is a free resource from my online course, From Idea To Launch, where I teach you how to build a full Laravel web application, step by step, at beginner's speed. Learn more →

Previously, I covered the high level design of a web app with controllers and views.

But there’s one more piece of the Model-View-Controller, or MVC, puzzle to include: the M, models.

A recap of an application with controllers and views

A web application using routes to detect URL-based requests; controllers to handle those requests; and views to render pages

A web application using routes to detect URL-based requests; controllers to handle those requests; and views to render pages

The image above depicts an application utilizing: routes to associate URLs with controllers; controllers to handle those user requests; and views to render pages:

  • Routes — associate URLs with controllers
  • Controller — handle user requests
  • View — render pages
  • Model — ? (the missing piece)

And it shows controllers interacting directly with a database. But in a full web application, this is done using the final third of the MVC trio: models.

Adding models to the mix

Models act as the middlemen between your controllers and your database, and are leveraged by controllers to interact with the database.

A complete MVC web application using routes to detect URL-based requests; controllers to handle those requests; models to retrieve data from the database; and views to render pages

A complete MVC web application using routes to detect URL-based requests; controllers to handle those requests; models to retrieve data from the database; and views to render pages

Your app should ultimate have one model for every different object type in your application.

For example, if you were building an application based on cars, you may have two different object types:

  • cars
  • manufacturers

In that case, you would create two models:

  • a Car model
  • a Manufacturer model

And each of those would be responsible for interacting with the database to retrieve any information for their respective object types — for example, the Car model would retrieve all car-related info.

So let’s review the complete request-fulfilling loop, with models included.

The complete MVC request-fulfilling loop

A user enters a URL in their browser that points to a web application, thus making a request.

That URL is matched to a route, which associates the URL with a designated controller action (i.e. a function in a controller).

The controller leverages the necessary models — which interact with the database — to retrieve the necessary information.

It then sends that information off to a view, which renders the request page for the user to view in their browser.

Request fulfilled!