SPEAKING ELOQUENT
ELOQUENTLY
Stephen
Afam‐Osemene
https://stephenafamo.com
@StephenAfamO
Thinking Eloquently
Accessors & Mutators
Scopes
Collections
Serialization
Events & Observers
Relationships
Mutators
OUTLINE
THINKING
ELOQUENTLY
THINKING ELOQUENTLY
Eloquent is not just a fancy
way of specifying the table
for the Query Builder
A Model, should enable us
retrieve and manipulate
EVERY information related
to it
THINKING ELOQUENTLY
Data manupulation belongs
in the Model
A model should completely
define a unit of DATA
THINKING ELOQUENTLY
ACCESSORS &
MUTATORS
ACCESSORS
Accessors allow us to
format our data when we
retrieve them
Instead of
ACCESSORS
$user = User::find(1);
echo "http://myapp.com" . $user‐>avatar;
ACCESSORS
We do
class User extends Model
{
public function getAvatarAttribute($value)
{
return "http://myapp.com/" . $value;
}
}
MUTATORS
Mutators allow us to
format our data when we
set them
Instead of
$user‐>name = ucfirst("stephen");
MUTATORS
We do
class User extends Model
{
public function setNameAttribute($value)
{
$this‐>attributes['name'] = ucfirst($value);
}
}
MUTATORS
SCOPES
SCOPES
Scopes are ways for us to
store restraints which we
can use repeatedly
SCOPES ‐ LOCAL
Local scopes are specific to
the model.
Although, we can always
extend the class ;‐﴿
SCOPES ‐ LOCAL
Do this once
class Developer extends Model
{
public function scopeSenior($query)
{
return $query‐>where('yrs_of_exp', '>', 3);
}
}
SCOPES ‐ LOCAL
Use anytime!
$senior_devs = AppDeveloper::senior()‐>get()
SCOPES ‐ LOCAL
We can accept additional
parameters to make our
scopes dynamic
SCOPES ‐ LOCAL
class Developer extends Model
{
public function scopeUses($query, $language)
{
return $query‐>where('language', $language);
}
}
Make it dynamic
SCOPES ‐ LOCAL
$php_devs = AppDeveloper::uses('php)‐>get()
Use anytime!
SCOPES ‐ GLOBAL
We can define a scope that
will be applied to all
queries by our Model
SCOPES ‐ GLOBAL
use IlluminateDatabaseEloquentScope;
class VerifiedScope implements Scope
{
public function apply($builder, $model)
{
$builder‐>where('verified', true);
}
}
Define the scope
class Developer extends Model
{
protected static function boot()
{
parent::boot();
static::addGlobalScope(new VerifiedScope);
}
}
SCOPES ‐ GLOBAL
Include the scope
SCOPES ‐ GLOBAL
Now all queries from our
Developer model will
retrieve only verified
entries.
SCOPES ‐ GLOBAL
// Global scope automatically applied
$verified_devs = Developer::get()
// Query without the Verified global scope
Developer::withoutGlobalScope(VerifiedScope::class)‐>get()
// Query without any global scope
Developer:: withoutGlobalScopes()‐>get()
Define the scope
COLLECTIONS
COLLECTIONS
Anytime multiple records
are retrieved, it is returned
as a COLLECTION of
Models
COLLECTIONS
Collections are
supercharged php arrays.
learn about it
https://laravel.com/docs/5.4/collections
COLLECTIONS
We can define a custom
Collection Object to be
returned by our model.
COLLECTIONS
use IlluminateSupportCollection;
class CustomCollection extends Collection
{
public function additionalMethod($var)
{
// do something unique
}
}
Define our new collection class
COLLECTIONS
Overwrite the newCollection method
class Developer extends Model
{
public function newCollection(array $models = [])
{
return new CustomCollection($models);
}
}
SERIALIZATION
SERIALIZATION
We can easily convert our
Model into an array or
JSON of it's attributes
SERIALIZATION
Easy!
$developer = AppDeveloper ::find(1);
// For arrays
$developer_array = $develooper‐>toArray();
// For JSON
$developer_json = $developer‐>toJson()
Sometimes we need to hide stuff so...
SERIALIZATION
class User extends Model
{
protected $hidden = ['age', 'address'];
// OR
protected $visible = ['company', 'name'];
}
Other times we want to access hidden
stuff so...
SERIALIZATION
$user = AppUser::find(1);
// maybe when the user is viewing
$with_age = $user‐>makeVisible('age')‐>toArray();
// for corporate reasons maybe ˉ_(ツ)_/ˉ
$without_company = $user‐>makeHidden('company')‐>toArray;
What if we just want to add stuff?
SERIALIZATION
class User extends Model
{
protected $appends = ['birth_year'];
public function getIBirthYearAttribute()
{
return date("Y") ‐ $this‐>age;
}
}
EVENTS & OBSERVERS
EVENTS & OBSERVERS
Laravel events are a great
way to subscribe and listen
for various events that
occur in our application.
https://laravel.com/docs/5.4/events
EVENTS & OBSERVERS
Eloquent models fire
several events.
We can map these events
to our event classes
EVENTS & OBSERVERS
Define the events property to map events
class User extends Model
{
protected $events = [
'saved' => UserSaved::class,
'deleted' => UserDeleted::class,
];
}
EVENTS & OBSERVERS
Full list of Eloquent events
creating created
updating updated
saving saved
deleting deleted
restoring restored
EVENTS & OBSERVERS
Observers are classes
whose sole purpose is to
listen to eloquent events
EVENTS & OBSERVERS
Create the Observer class
use AppMeetup;
class MeetupObserver
{
public function saving (Meetup $meetup)
{
// do something for the 'saving' event
// you an have more functions with 'event' names
}
}
EVENTS & OBSERVERS
Register the observer in a ServiceProvider
use AppMeetup;
class MyServiceProvider
{
public function boot ()
{
Meetup::observe(MeetupObserver::class);
}
}
RELATIONSHIPS
RELATIONSHIPS
Eloquent makes is really
easy to define and access
related models
RELATIONSHIPS ‐ 1‐1
One‐to‐One relationships
are where each model is
tied to one of the other
type
users
id ‐ integer
name ‐ string
contact
id ‐ integer
user_id ‐ integer
phone ‐ string
email ‐ string
website ‐ string
Example Database schema
RELATIONSHIPS ‐ 1‐1
Defining one side of the relationship
class User extends Model
{
public function contact()
{
return $this‐>hasOne('AppContact');
}
}
RELATIONSHIPS ‐ 1‐1
Defining the other side
class Contact extends Model
{
public function user()
{
return $this‐>belongsTo('AppUser');
}
}
RELATIONSHIPS ‐ 1‐1
$user = AppUser::find(1);
// Instead of
$contact = AppContact::select('contacts.*')
‐>where('user_id', '=', $user‐>id)
‐>first();
// We do
$contact = $user‐>contact;
RELATIONSHIPS ‐ 1‐1
RELATIONSHIPS ‐ 1‐n
One‐to‐Many relationships
are where one model is
linked to many of another
type
Example Database schema
users
id ‐ integer
name ‐ string
contact
id ‐ integer
user_id ‐ integer
type ‐ string
value ‐ string
RELATIONSHIPS ‐ 1‐n
Defining one side of the relationship
class User extends Model
{
public function contacts()
{
return $this‐>hasMany('AppContact');
}
}
RELATIONSHIPS ‐ 1‐n
Defining the other side
class Contact extends Model
{
public function user()
{
return $this‐>belongsTo('AppUser');
}
}
RELATIONSHIPS ‐ 1‐n
RELATIONSHIPS ‐ 1‐n
$user = AppUser::find(1);
// Instead of
$contacts = AppContact::select('contacts.*')
‐>where('user_id', '=', $user‐>id)
‐>get();
// We do
$contacts = $user‐>contacts;
RELATIONSHIPS ‐ n‐n
Many‐to‐Many
relationships are more
complicated
Example Database schema
users
id ‐ integer
name ‐ string
contact
id ‐ integer
user_id ‐ integer
type_id ‐ integer
value ‐ string
type
id ‐ integer
name ‐ string
RELATIONSHIPS ‐ n‐n
Defining one side of the relationship
class User extends Model
{
public function types()
{
return $this‐>belongsToMany('AppType')
‐>withPivot('id', 'value');
}
}
RELATIONSHIPS ‐ n‐n
Defining the other side
class Type extends Model
{
public function users()
{
return $this‐>belongsToMany('AppUser');
}
}
RELATIONSHIPS ‐ n‐n
RELATIONSHIPS ‐ 1‐n
// Instead of
$contacts = AppContact::select('contacts.*')
‐>join('types', 'contact.type_id', '=', 'types.id')
‐>where('user_id', '=', $user‐>id)
‐>where('type.name', '=', 'phone')
‐>get();
// We do
$types = $user‐>types;
//access throught the pivot property
RELATIONSHIPS ‐ distant
Distant relations can be
accessed easily by using
the hasManyThrough﴾﴿
relationship
Example Database schema
users
id ‐ integer
name ‐ string
posts
id ‐ integer
user_id ‐ integer
title ‐ string
body ‐ string
comments
id ‐ integer
post_id ‐ integer
title ‐ string
body ‐ string
RELATIONSHIPS ‐ distant
Defining the relationship
class User extends Model
{
public function comments()
{
return $this‐>hasManyThrough('AppPost', 'AppComment);
}
}
RELATIONSHIPS ‐ distant
// Instead of
$comments = AppComment::select('comments.*')
‐>join('posts', 'comment.post_id', '=', 'posts.id')
‐>join('users', 'post.user_id', '=', 'users.id')
‐>where('user_id', '=', $user‐>id)
‐>get();
// We do
$comments = $user‐>comments;
RELATIONSHIPS ‐ distant
RELATIONSHIPS ‐ morph
Polymorphic relationships
can save us from creating
many similar tables.
RELATIONSHIPS ‐ morph
We can allow more than
one model to relate with
our model.
Many applications
Example Database schema
users
id ‐ integer
name ‐ string
groups
id ‐ integer
name ‐ string
pictures
id ‐ integer
path‐ string
owner_id ‐ integer
owner_type ‐ string
RELATIONSHIPS ‐ morph
RELATIONSHIPS ‐ notes
Dynamic properties
$post‐>comments; //get all comments as a collection
$post‐>comments(); //returns a relationship class
// Can be used as query builders
$post‐>comments()‐>where('like', '>', 5);
RELATIONSHIPS ‐ notes
Check if it exists
Post::has('comments', '>=', 3)‐>get();
Post::doesntHave('comments')‐>get();
RELATIONSHIPS ‐ notes
Eager Loading
// Instead of this
$users = AppUser::all();
foreach ($users as $user) {
echo $user‐>contact‐>phone;
}
// We do this
$user = AppUser::with('contact')‐>get();
Inserting & Updating
create﴾﴿ save﴾﴿
associate﴾﴿ dissociate﴾﴿
attach﴾﴿ detach﴾﴿
sync﴾﴿ toggle﴾﴿
RELATIONSHIPS ‐ notes
We have many ways to modify relationships
RELATIONSHIPS ‐ notes
So many more lovely
capabilities.
https://laravel.com/docs/5.4/
eloquent‐relationships
QUESTIONS?
Twitter: @StephenAfamO
GitHub: @StephenAfamO
Website: https://stephenafamo.com
THANK YOU
Twitter: @StephenAfamO
GitHub: @StephenAfamO
Website: https://stephenafamo.com

More Related Content

PDF
Hibernate Mapping
PDF
Models Best Practices (ZF MVC)
PDF
MVC on the Server and on the Client: How to Integrate Spring MVC and Backbone...
PPTX
Injection de dépendances dans Symfony >= 3.3
PDF
How I started to love design patterns
PDF
TYPO3 Flow 2.0 (T3CON13 San Francisco)
PPTX
Java beans
PDF
Why is crud a bad idea - focus on real scenarios
Hibernate Mapping
Models Best Practices (ZF MVC)
MVC on the Server and on the Client: How to Integrate Spring MVC and Backbone...
Injection de dépendances dans Symfony >= 3.3
How I started to love design patterns
TYPO3 Flow 2.0 (T3CON13 San Francisco)
Java beans
Why is crud a bad idea - focus on real scenarios

What's hot (19)

PDF
Symfony Messenger (Symfony Live San Francisco)
PDF
Obect-Oriented Collaboration
PPTX
Sencha Touch - Introduction
PPTX
Hacking Your Way To Better Security - Dutch PHP Conference 2016
PDF
Demystifying oop
ODP
Symfony2, creare bundle e valore per il cliente
ODP
Rich domain model with symfony 2.5 and doctrine 2.5
PDF
Love and Loss: A Symfony Security Play
PPT
Introduction Php
PDF
Guard Authentication: Powerful, Beautiful Security
ODP
Drupal 8 Routing
PDF
Hooks and Events in Drupal 8
KEY
Zend Framework and the Doctrine2 MongoDB ODM (ZF1)
PDF
ZendCon2010 The Doctrine Project
PPT
Basic Oops concept of PHP
PPTX
Only oop
PDF
SOLID in Practice
PDF
Be RESTful (Symfony Camp 2008)
PDF
var, let in SIL
Symfony Messenger (Symfony Live San Francisco)
Obect-Oriented Collaboration
Sencha Touch - Introduction
Hacking Your Way To Better Security - Dutch PHP Conference 2016
Demystifying oop
Symfony2, creare bundle e valore per il cliente
Rich domain model with symfony 2.5 and doctrine 2.5
Love and Loss: A Symfony Security Play
Introduction Php
Guard Authentication: Powerful, Beautiful Security
Drupal 8 Routing
Hooks and Events in Drupal 8
Zend Framework and the Doctrine2 MongoDB ODM (ZF1)
ZendCon2010 The Doctrine Project
Basic Oops concept of PHP
Only oop
SOLID in Practice
Be RESTful (Symfony Camp 2008)
var, let in SIL
Ad

Similar to Speaking Eloquent Eloquently (20)

PPTX
Laravel
PDF
Simplified Guide on Using the Laravel Eloquent Relations!.pdf
PPTX
Introduction to laravel framework
PDF
Object Oriented Programming with Laravel - Session 6
PPTX
Hacking Laravel - Custom Relationships with Eloquent
PDF
Advanced Interfaces and Repositories in Laravel
PPTX
Laravel for Web Artisans
PPTX
laravel-53
PDF
Laravel 101
PDF
Best Laravel Eloquent Tips and Tricks
PDF
Object Oriented Programming with Laravel - Session 5
PPTX
Webinar: Schema Design
PDF
MongoDB Schema Design (Event: An Evening with MongoDB Houston 3/11/15)
PDF
Laravel Level 1 (The Basic)
PPTX
Building Large Scale PHP Web Applications with Laravel 4
PDF
GraphQL-PHP: Dos and don'ts
PPTX
Schema design mongo_boston
PDF
Laravelcollectionsunraveled
PDF
Laravel intake 37 all days
PPTX
Laravel Eloquent ORM
Laravel
Simplified Guide on Using the Laravel Eloquent Relations!.pdf
Introduction to laravel framework
Object Oriented Programming with Laravel - Session 6
Hacking Laravel - Custom Relationships with Eloquent
Advanced Interfaces and Repositories in Laravel
Laravel for Web Artisans
laravel-53
Laravel 101
Best Laravel Eloquent Tips and Tricks
Object Oriented Programming with Laravel - Session 5
Webinar: Schema Design
MongoDB Schema Design (Event: An Evening with MongoDB Houston 3/11/15)
Laravel Level 1 (The Basic)
Building Large Scale PHP Web Applications with Laravel 4
GraphQL-PHP: Dos and don'ts
Schema design mongo_boston
Laravelcollectionsunraveled
Laravel intake 37 all days
Laravel Eloquent ORM
Ad

Recently uploaded (20)

PDF
SOFTWARE ENGINEERING Software Engineering (3rd Edition) by K.K. Aggarwal & Yo...
PPTX
Cybersecurity-and-Fraud-Protecting-Your-Digital-Life.pptx
PPTX
DevOpsDays Halifax 2025 - Building 10x Organizations Using Modern Productivit...
PPTX
4Seller: The All-in-One Multi-Channel E-Commerce Management Platform for Glob...
PPTX
Python is a high-level, interpreted programming language
PDF
Website Design & Development_ Professional Web Design Services.pdf
PDF
Understanding the Need for Systemic Change in Open Source Through Intersectio...
PPTX
string python Python Strings: Literals, Slicing, Methods, Formatting, and Pra...
PDF
CCleaner 6.39.11548 Crack 2025 License Key
PDF
infoteam HELLAS company profile 2025 presentation
PPTX
R-Studio Crack Free Download 2025 Latest
PPTX
Plex Media Server 1.28.2.6151 With Crac5 2022 Free .
PDF
Microsoft Office 365 Crack Download Free
PPTX
ROI Analysis for Newspaper Industry with Odoo ERP
PDF
Introduction to Ragic - #1 No Code Tool For Digitalizing Your Business Proces...
PPTX
Matchmaking for JVMs: How to Pick the Perfect GC Partner
PDF
Multiverse AI Review 2025: Access All TOP AI Model-Versions!
PDF
Sun and Bloombase Spitfire StoreSafe End-to-end Storage Security Solution
PPTX
Download Adobe Photoshop Crack 2025 Free
PDF
E-Commerce Website Development Companyin india
SOFTWARE ENGINEERING Software Engineering (3rd Edition) by K.K. Aggarwal & Yo...
Cybersecurity-and-Fraud-Protecting-Your-Digital-Life.pptx
DevOpsDays Halifax 2025 - Building 10x Organizations Using Modern Productivit...
4Seller: The All-in-One Multi-Channel E-Commerce Management Platform for Glob...
Python is a high-level, interpreted programming language
Website Design & Development_ Professional Web Design Services.pdf
Understanding the Need for Systemic Change in Open Source Through Intersectio...
string python Python Strings: Literals, Slicing, Methods, Formatting, and Pra...
CCleaner 6.39.11548 Crack 2025 License Key
infoteam HELLAS company profile 2025 presentation
R-Studio Crack Free Download 2025 Latest
Plex Media Server 1.28.2.6151 With Crac5 2022 Free .
Microsoft Office 365 Crack Download Free
ROI Analysis for Newspaper Industry with Odoo ERP
Introduction to Ragic - #1 No Code Tool For Digitalizing Your Business Proces...
Matchmaking for JVMs: How to Pick the Perfect GC Partner
Multiverse AI Review 2025: Access All TOP AI Model-Versions!
Sun and Bloombase Spitfire StoreSafe End-to-end Storage Security Solution
Download Adobe Photoshop Crack 2025 Free
E-Commerce Website Development Companyin india

Speaking Eloquent Eloquently