Skip to main content

Black Friday 2025! Only until December 1st: coupon FRIDAY25 for 40% off Yearly/Lifetime membership!

Read more here
Premium Members Only
Join to unlock this tutorial and all of our courses.
Tutorial Premium Tutorial

Design Patterns: Examples from Laravel Framework Core

March 30, 2023
9 min read

Wanna learn design patterns? Here's a "secret": you've all actually USED them already while working with Laravel itself. Let's see the examples of patterns like Facade, Builder, and Adapter in the framework code.


Builder Pattern

The most common and familiar Builder pattern is the Query Builder in Laravel. Of course, it is extended by Eloquent Models but the core example is still the Query Builder. Let's look at the example:

Let's get a basic example:

Query Builder

DB::table('users')
->where('name', 'John')
->where('age', '>', 18)
->orderBy('age')
->get();

So what did we do, and why is it a Builder? We've built a query by chaining methods on top of a base. So what does it do under the hood? Let's look at the example:

  • DB::table('users') - We indicate that we will work with the users table
  • ->where('name', 'John') - Added a condition that only John users should be selected
  • ->where('age', '>', 18) - Added a condition that only users with an age greater than 18 should be selected
  • ->orderBy('age') - Order the users by age
  • ->get() - Executed the query and retrieved the results from the database

Each of these individual blocks will append to a raw SQL query as we are building it in parts. Think about it like this:

  • DB::table('users') - SELECT * FROM users...
  • ->where('name', 'John') - ...WHERE name = 'John'...
  • ->where('age', '>', 18) - ...WHERE name = 'John' AND age > 18...
  • ->orderBy('age') - ...ORDER BY age...
  • ->get() - SELECT * FROM users WHERE name = 'John' AND age > 18 ORDER BY age

If we want to look at how we are building an update query we can look at...

Premium Members Only

This advanced tutorial is available exclusively to Laravel Daily Premium members.

Premium membership includes:

Access to all premium tutorials
Video and Text Courses
Private Discord Channel

Comments & Discussion

ND
Nico Deblauwe ✓ Link copied!

Small typo in last paragraph of observer pattern "will not generate"... Remove not -->And feel free to delete this comment after correcting

PK
Povilas Korop ✓ Link copied!

It was supposed to be "now", fixed, thanks :)

JM
Jose Maria ✓ Link copied!

Great article. Thanks !

H
hariharan2684 ✓ Link copied!

We know.. but we don't know.. you are unearthing .. Thanks very much

We'd Love Your Feedback

Tell us what you like or what we can improve

Feel free to share anything you like or dislike about this page or the platform in general.