SlideShare a Scribd company logo
LARAVEL FRAMEWORK
DB OPERATIONS
ELOQUENT MODEL
Sayed Ahmed
Computer Engineering, BUET, Bangladesh (Graduated on
2001)
MSc., Computer Science, Canada
http://www.justetc.net
INSTALLING
 You can install by using Composer
 http://getcomposer.org/doc/00-intro.md
DB STUFF
 How and where to configure
 app/config/database.php
 Supported Databases
 MySQL, Postgres, SQLite, and SQL Server
 Running A Select Query
 $results = DB::select('select * from users where id =
?', array(1));
 Running An Insert Statement
 DB::insert('insert into users (id, name) values (?, ?)',
array(1, 'Dayle'));
DB STUFF
 Running An Update Statement
 DB::update('update users set votes = 100 where
name = ?', array('John'));
 Running A General Statement
 DB::statement('drop table users');
 Listening For Query Events
 DB::listen(function($sql, $bindings, $time) { // });
DB STUFF
 Database transactions
 DB::transaction(function() {
 DB::table('users')->update(array('votes' => 1));
 DB::table('posts')->delete();
 })
 Access Connections
 $users = DB::connection('foo')->select(...);
 Access raw PDO instance
 $pdo = DB::connection()->getPdo()
 Reconnect
 DB::reconnect('foo');
DB STUFF
 Query Logging
 DB::connection()->disableQueryLog();
 $queries = DB::getQueryLog();
 Note: QueryLogging is enabled by default
QUERY BUILDER
 Select : All Rows
 $users = DB::table('users')->get();
 foreach ($users as $user) {
 var_dump($user->name);
 }
 Single Row
 $user = DB::table('users')->where('name',
'John')->first();
 var_dump($user->name);
QUERY BUILDER
 Single column from a row
 $name = DB::table('users')->where('name', 'John')-
>pluck('name');
 A List Of Column Values
 $roles = DB::table('roles')->lists('title');
 $roles = DB::table('roles')->lists('title', 'name');
 $users = DB::table('users')->select('name', 'email')-
>get();
 $users = DB::table('users')->distinct()->get();
 -$users = DB::table('users')->select('name as
user_name')->get();
QUERY BUILDER
 Where
 $users = DB::table('users')->where('votes', '>',
100)->get();
 $users = DB::table('users') ->where('votes', '>',
100) ->orWhere('name', 'John') ->get();
 Order by, group by
 $users = DB::table('users') ->orderBy('name',
'desc') ->groupBy('count') ->having('count', '>',
100) ->get();
QUERY BUILDER
 Offset and limit
 $users = DB::table('users')->skip(10)->take(5)-
>get();
JOINS
 Basic
 DB::table('users') ->join('contacts', 'users.id', '=',
'contacts.user_id') ->join('orders', 'users.id', '=',
'orders.user_id') ->select('users.id',
'contacts.phone', 'orders.price');
 Left
 DB::table('users') ->leftJoin('posts', 'users.id', '=',
'posts.user_id') ->get();
JOINS
 Complex
 DB::table('users') ->join('contacts', function($join)
{ $join->on('users.id', '=',
'contacts.user_id')- >orOn(...);
 }) ->get();
OTHERS
 Advanced whereas
 DB::table('users') ->where('name', '=', 'John') -
>orWhere(function($query) { $query-
>where('votes', '>', 100) ->where('title', '<>',
'Admin'); }) ->get();
 Exists
 DB::table('users') ->whereExists(function($query)
{ $query->select(DB::raw(1)) ->from('orders') -
>whereRaw('orders.user_id = users.id'); }) -
>get();
AGGREGATE METHODS
 $users = DB::table('users')->count();
 $price = DB::table('orders')->max('price');
 $price = DB::table('orders')->min('price');
 $price = DB::table('orders')->avg('price');
 $total = DB::table('users')->sum('votes');
QUERY BUILDERS
 Raw Expressions
 $users = DB::table('users')
 ->select(DB::raw('count(*) as user_count,
status'))
 ->where('status', '<>', 1) ->groupBy('status') -
>get();
INCREMENT/DECREMENT
 DB::table('users')->increment('votes');
 DB::table('users')->increment('votes', 5);
 DB::table('users')->decrement('votes');
 DB::table('users')->decrement('votes', 5);
 DB::table('users')->increment('votes', 1,
array('name' => 'John'));
INSERTS
 Inserting Records into a table
 DB::table('users')->insert( array('email' =>
'john@example.com', 'votes' => 0) );
 $id = DB::table('users')->insertGetId(
array('email' => 'john@example.com', 'votes' =>
0) );
 DB::table('users')->insert(array( array('email' =>
'taylor@example.com', 'votes' => 0), array('email'
=> 'dayle@example.com', 'votes' => 0), ));
UPDATES
 DB::table('users') ->where('id', 1) -
>update(array('votes' => 1));
 Deletes
 DB::table('users')->where('votes', '<', 100)-
>delete();
 DB::table('users')->delete();
 DB::table('users')->truncate();
UNIONS
 $first = DB::table('users')
 ->whereNull('first_name');
 $users = DB::table('users')
 ->whereNull('last_name')->union($first)->get();
 Caching Results
 $users = DB::table('users')->remember(10)-
>get();
 Remember for 10 minutes
ELOQUENT ORM
 The Eloquent ORM included with Laravel
provides a beautiful, simple ActiveRecord
implementation for working with your
database. Each database table has a
corresponding "Model" which is used to
interact with that table.
ELOQUENT MODEL
 Defining An Eloquent Model
 class User extends Eloquent {}
 By default it will point to the table users
 Lowercase and plural form
 class User extends Eloquent {
 protected $table = 'my_users';
 }
 Note: you can use properties such as primaryKey
and connection
 All table should have createdat and updatedat
columns else use $timestamps = false in the model
ELOQUENT MODEL AND DB OPERATIONS
 Retrieve All
 $users = User::all();
 Retrieve by Primary key
 $user = User::find(1);
 var_dump($user->name);
 Retrieve or Throw exception
 $model = User::findOrFail(1); $model =
User::where('votes', '>', 100)->firstOrFail();
HANDLING EXCEPTIONS
 Handling Exceptions
 use
IlluminateDatabaseEloquentModelNotFoundEx
ception;
App::error(function(ModelNotFoundException
$e) { return Response::make('Not Found', 404);
});
QUERYING
 Querying
 $users = User::where('votes', '>', 100)->take(10)-
>get(); foreach ($users as $user) {
var_dump($user->name); }
 Aggregates
 $count = User::where('votes', '>', 100)->count();
 $users = User::whereRaw('age > ? and votes = 100',
array(25))->get();
 Connection to use
 $user = User::on('connection-name')->find(1);
FILLABLE
 The fillable property specifies which attributes
should be mass-assignable. This can be set at
the class or instance level.
 class User extends Eloquent {
 protected $fillable = array('first_name', 'last_name',
'email'); }
 Guarded (not mass assignable)
 class User extends Eloquent {
 protected $guarded = array('id', 'password');
 }
BLOCKING AND INSERTION
 Block all attributes from mass assignment
 protected $guarded = array('*');
 Insert a new row
 $user = new User;
 $user->name = 'John';
 $user->save();
UPDATE A ROW
 $user = User::create(array('name' =>
'John'));
 Updating a retrieved model
 $user = User::find(1); $user->email =
'john@foo.com'; $user->save();
SOME SAVE, UPDATE, DELETE STUFF
 Saving a model and relationship
 $user->push();
 Updates as queries
 $affectedRows = User::where('votes', '>', 100)
 ->update(array('status' => 2));
 Delete by key
 User::destroy(1);
 User::destroy(array(1, 2, 3));
 User::destroy(1, 2, 3);
 Updating Model’s Timestamp
 $user->touch();
 Soft Delete
 class User extends Eloquent { protected $softDelete
= true; }
 $table->softDeletes();
 Soft deleted stuff into results (trashed + untrashed)
 $table->softDeletes();
 Only Trashed
 $users = User::onlyTrashed()->where('account_id', 1)-
>get();
 Restore softdeleted into active
 $user->restore();
 On query
 User::withTrashed()->where('account_id', 1)-
>restore();
 On relationships
 $user->posts()->restore();
FORCEDELETE
 $user->forceDelete();
 $user->posts()->forceDelete();
QUERY SCOPES
 Like variable Scope
 Define query scope
 class User extends Eloquent {
 public function scopePopular($query) {
 return $query->where('votes', '>', 100);
 }
 public function scopeWomen($query) {
 return $query->whereGender('W');
 }
 }
 Utilize Query Scopes
 $users = User::popular()->women()-
>orderBy('created_at')->get();
 Dynamic Scopes
 class User extends Eloquent {
 public function scopeOfType($query, $type) {
 return $query->whereType($type);
 }
 }
 $users = User::ofType('member')->get();
RELATIONSHIPS
 One To One
 One To Many
 Many To Many
 Polymorphic Relations
DEFINE ONE TO ONE
 class User extends Eloquent {
 public function phone() {
 return $this->hasOne('Phone');
 }
 }
 Use
 $phone = User::find(1)->phone;
INVERSE OF A RELATION
 class Phone extends Eloquent {
 public function user() {
 return $this->belongsTo('User');
 }
 }
 class Phone extends Eloquent {
 public function user() {
 return $this->belongsTo('User', 'custom_key');
 }
 }`
 class Phone extends Eloquent {
 public function user() {
 return $this->belongsTo('User', 'custom_key');
 }
 }
ONE TO MANY
 class Post extends Eloquent {
 public function comments() {
 return $this->hasMany('Comment');
 }
 }
 return $this->hasMany('Comment',
'custom_key');
 $comments = Post::find(1)->comments;
 $comments = Post::find(1)->comments()
 ->where('title', '=', 'foo')->first();
INVERSE OF A RELATION
 class Comment extends Eloquent {
 public function post() {
 return $this->belongsTo('Post');
 }
 }
MANY TO MANY
 class User extends Eloquent {
 public function roles() {
 return $this->belongsToMany('Role');
 }
 }
 return $this->belongsToMany('Role',
'user_roles');
 return $this->belongsToMany('Role',
'user_roles', 'user_id', 'foo_id');
 $roles = User::find(1)->roles;
INVERSE OF A RELATION
 class Role extends Eloquent {
 public function users() {
 return $this->belongsToMany('User');
 }
 }
POLYMORPHIC RELATIONS
 Polymorphic relations allow a model to
belong to more than one other model, on a
single association.
 class Photo extends Eloquent { public
function imageable() { return $this-
>morphTo(); } } class Staff extends Eloquent
{ public function photos() { return $this-
>morphMany('Photo', 'imageable'); } } class
Order extends Eloquent { public function
photos() { return $this->morphMany('Photo',
'imageable'); } }
USE
 $staff = Staff::find(1); foreach ($staff->photos
as $photo) { // }
 $photo = Photo::find(1);
 $imageable = $photo->imageable;
QUERYING RELATIONS
 $posts = Post::has('comments')->get()
 $posts = Post::has('comments', '>=', 3)-
>get();
DYNAMIC PROPERTIES
 Eloquent allows you to access your relations
via dynamic properties. Eloquent will
automatically load the relationship for you,
and is even smart enough to know whether
to call the get (for one-to-many relationships)
or first (for one-to-one relationships) method
EAGER LOADING
 Will hit db 26 times for 25 books
 foreach (Book::all() as $book) { echo $book-
>author->name; }
 Is reduced to two queries
 foreach (Book::with('author')->get() as $book) {
echo $book->author->name; }
 select * from books select * from authors where
id in (1, 2, 3, 4, 5, ...)
 With constraints
 $users = User::with(array('posts' =>
function($query) { $query->where('title', 'like',
'%first%'); }))->get();
MUST SEE
 http://codehappy.daylerees.com/eloquent-
orm
 http://net.tutsplus.com/tutorials/php/build-
web-apps-from-scratch-with-laravel-the-
eloquent-orm/

More Related Content

What's hot

Dependency Injection with PHP and PHP 5.3
Dependency Injection with PHP and PHP 5.3Dependency Injection with PHP and PHP 5.3
Dependency Injection with PHP and PHP 5.3
Fabien Potencier
 
The State of Lithium
The State of LithiumThe State of Lithium
The State of Lithium
Nate Abele
 
Unit testing zend framework apps
Unit testing zend framework appsUnit testing zend framework apps
Unit testing zend framework apps
Michelangelo van Dam
 
Presentation1
Presentation1Presentation1
Presentation1
Rahadyan Gusti
 
Database API, your new friend
Database API, your new friendDatabase API, your new friend
Database API, your new friend
kikoalonsob
 
購物車程式架構簡介
購物車程式架構簡介購物車程式架構簡介
購物車程式架構簡介
Jace Ju
 
CakeFest 2013 keynote
CakeFest 2013 keynoteCakeFest 2013 keynote
CakeFest 2013 keynote
José Lorenzo Rodríguez Urdaneta
 
PHP Data Objects
PHP Data ObjectsPHP Data Objects
PHP Data Objects
Wez Furlong
 
Taming Command Bus
Taming Command BusTaming Command Bus
Taming Command Bus
Krzysztof Menżyk
 
Intro programacion funcional
Intro programacion funcionalIntro programacion funcional
Intro programacion funcional
NSCoder Mexico
 
Oops in php
Oops in phpOops in php
Revisiting SOLID Principles
Revisiting  SOLID Principles Revisiting  SOLID Principles
Revisiting SOLID Principles
Anis Ahmad
 
Agile database access with CakePHP 3
Agile database access with CakePHP 3Agile database access with CakePHP 3
Agile database access with CakePHP 3
José Lorenzo Rodríguez Urdaneta
 
DrupalCamp Foz - Novas APIs Drupal 7
DrupalCamp Foz - Novas APIs Drupal 7DrupalCamp Foz - Novas APIs Drupal 7
DrupalCamp Foz - Novas APIs Drupal 7
chuvainc
 
Drupal II: The SQL
Drupal II: The SQLDrupal II: The SQL
Drupal II: The SQL
ddiers
 
PHP tips and tricks
PHP tips and tricks PHP tips and tricks
PHP tips and tricks
Damien Seguy
 
Designing Opeation Oriented Web Applications / YAPC::Asia Tokyo 2011
Designing Opeation Oriented Web Applications / YAPC::Asia Tokyo 2011Designing Opeation Oriented Web Applications / YAPC::Asia Tokyo 2011
Designing Opeation Oriented Web Applications / YAPC::Asia Tokyo 2011
Masahiro Nagano
 
SOLID in Practice
SOLID in PracticeSOLID in Practice
SOLID in Practice
Jessica Mauerhan
 
Drupal - dbtng 25th Anniversary Edition
Drupal - dbtng 25th Anniversary EditionDrupal - dbtng 25th Anniversary Edition
Drupal - dbtng 25th Anniversary Edition
ddiers
 
Advanced Querying with CakePHP 3
Advanced Querying with CakePHP 3Advanced Querying with CakePHP 3
Advanced Querying with CakePHP 3
José Lorenzo Rodríguez Urdaneta
 

What's hot (20)

Dependency Injection with PHP and PHP 5.3
Dependency Injection with PHP and PHP 5.3Dependency Injection with PHP and PHP 5.3
Dependency Injection with PHP and PHP 5.3
 
The State of Lithium
The State of LithiumThe State of Lithium
The State of Lithium
 
Unit testing zend framework apps
Unit testing zend framework appsUnit testing zend framework apps
Unit testing zend framework apps
 
Presentation1
Presentation1Presentation1
Presentation1
 
Database API, your new friend
Database API, your new friendDatabase API, your new friend
Database API, your new friend
 
購物車程式架構簡介
購物車程式架構簡介購物車程式架構簡介
購物車程式架構簡介
 
CakeFest 2013 keynote
CakeFest 2013 keynoteCakeFest 2013 keynote
CakeFest 2013 keynote
 
PHP Data Objects
PHP Data ObjectsPHP Data Objects
PHP Data Objects
 
Taming Command Bus
Taming Command BusTaming Command Bus
Taming Command Bus
 
Intro programacion funcional
Intro programacion funcionalIntro programacion funcional
Intro programacion funcional
 
Oops in php
Oops in phpOops in php
Oops in php
 
Revisiting SOLID Principles
Revisiting  SOLID Principles Revisiting  SOLID Principles
Revisiting SOLID Principles
 
Agile database access with CakePHP 3
Agile database access with CakePHP 3Agile database access with CakePHP 3
Agile database access with CakePHP 3
 
DrupalCamp Foz - Novas APIs Drupal 7
DrupalCamp Foz - Novas APIs Drupal 7DrupalCamp Foz - Novas APIs Drupal 7
DrupalCamp Foz - Novas APIs Drupal 7
 
Drupal II: The SQL
Drupal II: The SQLDrupal II: The SQL
Drupal II: The SQL
 
PHP tips and tricks
PHP tips and tricks PHP tips and tricks
PHP tips and tricks
 
Designing Opeation Oriented Web Applications / YAPC::Asia Tokyo 2011
Designing Opeation Oriented Web Applications / YAPC::Asia Tokyo 2011Designing Opeation Oriented Web Applications / YAPC::Asia Tokyo 2011
Designing Opeation Oriented Web Applications / YAPC::Asia Tokyo 2011
 
SOLID in Practice
SOLID in PracticeSOLID in Practice
SOLID in Practice
 
Drupal - dbtng 25th Anniversary Edition
Drupal - dbtng 25th Anniversary EditionDrupal - dbtng 25th Anniversary Edition
Drupal - dbtng 25th Anniversary Edition
 
Advanced Querying with CakePHP 3
Advanced Querying with CakePHP 3Advanced Querying with CakePHP 3
Advanced Querying with CakePHP 3
 

Similar to Laravel

Doctrine For Beginners
Doctrine For BeginnersDoctrine For Beginners
Doctrine For Beginners
Jonathan Wage
 
Crafting beautiful software
Crafting beautiful softwareCrafting beautiful software
Crafting beautiful software
Jorn Oomen
 
Dependency Injection
Dependency InjectionDependency Injection
Dependency Injection
Rifat Nabi
 
PHPUnit でよりよくテストを書くために
PHPUnit でよりよくテストを書くためにPHPUnit でよりよくテストを書くために
PHPUnit でよりよくテストを書くために
Yuya Takeyama
 
Tidy Up Your Code
Tidy Up Your CodeTidy Up Your Code
Tidy Up Your Code
Abbas Ali
 
Php update and delet operation
Php update and delet operationPhp update and delet operation
Php update and delet operation
syeda zoya mehdi
 
laravel tricks in 50minutes
laravel tricks in 50minuteslaravel tricks in 50minutes
laravel tricks in 50minutes
Barang CK
 
PHPUnit elevato alla Symfony2
PHPUnit elevato alla Symfony2PHPUnit elevato alla Symfony2
PHPUnit elevato alla Symfony2
eugenio pombi
 
Unit testing with zend framework tek11
Unit testing with zend framework tek11Unit testing with zend framework tek11
Unit testing with zend framework tek11
Michelangelo van Dam
 
Unit testing with zend framework PHPBenelux
Unit testing with zend framework PHPBeneluxUnit testing with zend framework PHPBenelux
Unit testing with zend framework PHPBenelux
Michelangelo van Dam
 
Silex meets SOAP & REST
Silex meets SOAP & RESTSilex meets SOAP & REST
Silex meets SOAP & REST
Hugo Hamon
 
Introduction to laravel framework
Introduction to laravel frameworkIntroduction to laravel framework
Introduction to laravel framework
Ahmad Fatoni
 
Durian: a PHP 5.5 microframework with generator-style middleware
Durian: a PHP 5.5 microframework with generator-style middlewareDurian: a PHP 5.5 microframework with generator-style middleware
Durian: a PHP 5.5 microframework with generator-style middleware
Kuan Yen Heng
 
Easy rest service using PHP reflection api
Easy rest service using PHP reflection apiEasy rest service using PHP reflection api
Easy rest service using PHP reflection api
Matthieu Aubry
 
Virtual Madness @ Etsy
Virtual Madness @ EtsyVirtual Madness @ Etsy
Virtual Madness @ Etsy
Nishan Subedi
 
Rich domain model with symfony 2.5 and doctrine 2.5
Rich domain model with symfony 2.5 and doctrine 2.5Rich domain model with symfony 2.5 and doctrine 2.5
Rich domain model with symfony 2.5 and doctrine 2.5
Leonardo Proietti
 
Symfony2 Building on Alpha / Beta technology
Symfony2 Building on Alpha / Beta technologySymfony2 Building on Alpha / Beta technology
Symfony2 Building on Alpha / Beta technology
Daniel Knell
 
The History of PHPersistence
The History of PHPersistenceThe History of PHPersistence
The History of PHPersistence
Hugo Hamon
 
Mocking Dependencies in PHPUnit
Mocking Dependencies in PHPUnitMocking Dependencies in PHPUnit
Mocking Dependencies in PHPUnit
mfrost503
 
Adding Dependency Injection to Legacy Applications
Adding Dependency Injection to Legacy ApplicationsAdding Dependency Injection to Legacy Applications
Adding Dependency Injection to Legacy Applications
Sam Hennessy
 

Similar to Laravel (20)

Doctrine For Beginners
Doctrine For BeginnersDoctrine For Beginners
Doctrine For Beginners
 
Crafting beautiful software
Crafting beautiful softwareCrafting beautiful software
Crafting beautiful software
 
Dependency Injection
Dependency InjectionDependency Injection
Dependency Injection
 
PHPUnit でよりよくテストを書くために
PHPUnit でよりよくテストを書くためにPHPUnit でよりよくテストを書くために
PHPUnit でよりよくテストを書くために
 
Tidy Up Your Code
Tidy Up Your CodeTidy Up Your Code
Tidy Up Your Code
 
Php update and delet operation
Php update and delet operationPhp update and delet operation
Php update and delet operation
 
laravel tricks in 50minutes
laravel tricks in 50minuteslaravel tricks in 50minutes
laravel tricks in 50minutes
 
PHPUnit elevato alla Symfony2
PHPUnit elevato alla Symfony2PHPUnit elevato alla Symfony2
PHPUnit elevato alla Symfony2
 
Unit testing with zend framework tek11
Unit testing with zend framework tek11Unit testing with zend framework tek11
Unit testing with zend framework tek11
 
Unit testing with zend framework PHPBenelux
Unit testing with zend framework PHPBeneluxUnit testing with zend framework PHPBenelux
Unit testing with zend framework PHPBenelux
 
Silex meets SOAP & REST
Silex meets SOAP & RESTSilex meets SOAP & REST
Silex meets SOAP & REST
 
Introduction to laravel framework
Introduction to laravel frameworkIntroduction to laravel framework
Introduction to laravel framework
 
Durian: a PHP 5.5 microframework with generator-style middleware
Durian: a PHP 5.5 microframework with generator-style middlewareDurian: a PHP 5.5 microframework with generator-style middleware
Durian: a PHP 5.5 microframework with generator-style middleware
 
Easy rest service using PHP reflection api
Easy rest service using PHP reflection apiEasy rest service using PHP reflection api
Easy rest service using PHP reflection api
 
Virtual Madness @ Etsy
Virtual Madness @ EtsyVirtual Madness @ Etsy
Virtual Madness @ Etsy
 
Rich domain model with symfony 2.5 and doctrine 2.5
Rich domain model with symfony 2.5 and doctrine 2.5Rich domain model with symfony 2.5 and doctrine 2.5
Rich domain model with symfony 2.5 and doctrine 2.5
 
Symfony2 Building on Alpha / Beta technology
Symfony2 Building on Alpha / Beta technologySymfony2 Building on Alpha / Beta technology
Symfony2 Building on Alpha / Beta technology
 
The History of PHPersistence
The History of PHPersistenceThe History of PHPersistence
The History of PHPersistence
 
Mocking Dependencies in PHPUnit
Mocking Dependencies in PHPUnitMocking Dependencies in PHPUnit
Mocking Dependencies in PHPUnit
 
Adding Dependency Injection to Legacy Applications
Adding Dependency Injection to Legacy ApplicationsAdding Dependency Injection to Legacy Applications
Adding Dependency Injection to Legacy Applications
 

More from Sayed Ahmed

Workplace, Data Analytics, and Ethics
Workplace, Data Analytics, and EthicsWorkplace, Data Analytics, and Ethics
Workplace, Data Analytics, and Ethics
Sayed Ahmed
 
Python py charm anaconda jupyter installation and basic commands
Python py charm anaconda jupyter   installation and basic commandsPython py charm anaconda jupyter   installation and basic commands
Python py charm anaconda jupyter installation and basic commands
Sayed Ahmed
 
[not edited] Demo on mobile app development using ionic framework
[not edited] Demo on mobile app development using ionic framework[not edited] Demo on mobile app development using ionic framework
[not edited] Demo on mobile app development using ionic framework
Sayed Ahmed
 
Sap hana-ide-overview-nodev
Sap hana-ide-overview-nodevSap hana-ide-overview-nodev
Sap hana-ide-overview-nodev
Sayed Ahmed
 
Invest wisely
Invest wiselyInvest wisely
Invest wisely
Sayed Ahmed
 
Will be an introduction to
Will be an introduction toWill be an introduction to
Will be an introduction to
Sayed Ahmed
 
Whm and cpanel overview hosting control panel overview
Whm and cpanel overview   hosting control panel overviewWhm and cpanel overview   hosting control panel overview
Whm and cpanel overview hosting control panel overview
Sayed Ahmed
 
Web application development using zend framework
Web application development using zend frameworkWeb application development using zend framework
Web application development using zend framework
Sayed Ahmed
 
Web design and_html_part_3
Web design and_html_part_3Web design and_html_part_3
Web design and_html_part_3
Sayed Ahmed
 
Web design and_html_part_2
Web design and_html_part_2Web design and_html_part_2
Web design and_html_part_2
Sayed Ahmed
 
Web design and_html
Web design and_htmlWeb design and_html
Web design and_html
Sayed Ahmed
 
Visual studio ide shortcuts
Visual studio ide shortcutsVisual studio ide shortcuts
Visual studio ide shortcuts
Sayed Ahmed
 
Virtualization
VirtualizationVirtualization
Virtualization
Sayed Ahmed
 
User interfaces
User interfacesUser interfaces
User interfaces
Sayed Ahmed
 
Unreal
UnrealUnreal
Unreal
Sayed Ahmed
 
Unit tests in_symfony
Unit tests in_symfonyUnit tests in_symfony
Unit tests in_symfony
Sayed Ahmed
 
Telerik this is sayed
Telerik this is sayedTelerik this is sayed
Telerik this is sayed
Sayed Ahmed
 
System analysis and_design
System analysis and_designSystem analysis and_design
System analysis and_design
Sayed Ahmed
 
Symfony 2
Symfony 2Symfony 2
Symfony 2
Sayed Ahmed
 
Story telling and_narrative
Story telling and_narrativeStory telling and_narrative
Story telling and_narrative
Sayed Ahmed
 

More from Sayed Ahmed (20)

Workplace, Data Analytics, and Ethics
Workplace, Data Analytics, and EthicsWorkplace, Data Analytics, and Ethics
Workplace, Data Analytics, and Ethics
 
Python py charm anaconda jupyter installation and basic commands
Python py charm anaconda jupyter   installation and basic commandsPython py charm anaconda jupyter   installation and basic commands
Python py charm anaconda jupyter installation and basic commands
 
[not edited] Demo on mobile app development using ionic framework
[not edited] Demo on mobile app development using ionic framework[not edited] Demo on mobile app development using ionic framework
[not edited] Demo on mobile app development using ionic framework
 
Sap hana-ide-overview-nodev
Sap hana-ide-overview-nodevSap hana-ide-overview-nodev
Sap hana-ide-overview-nodev
 
Invest wisely
Invest wiselyInvest wisely
Invest wisely
 
Will be an introduction to
Will be an introduction toWill be an introduction to
Will be an introduction to
 
Whm and cpanel overview hosting control panel overview
Whm and cpanel overview   hosting control panel overviewWhm and cpanel overview   hosting control panel overview
Whm and cpanel overview hosting control panel overview
 
Web application development using zend framework
Web application development using zend frameworkWeb application development using zend framework
Web application development using zend framework
 
Web design and_html_part_3
Web design and_html_part_3Web design and_html_part_3
Web design and_html_part_3
 
Web design and_html_part_2
Web design and_html_part_2Web design and_html_part_2
Web design and_html_part_2
 
Web design and_html
Web design and_htmlWeb design and_html
Web design and_html
 
Visual studio ide shortcuts
Visual studio ide shortcutsVisual studio ide shortcuts
Visual studio ide shortcuts
 
Virtualization
VirtualizationVirtualization
Virtualization
 
User interfaces
User interfacesUser interfaces
User interfaces
 
Unreal
UnrealUnreal
Unreal
 
Unit tests in_symfony
Unit tests in_symfonyUnit tests in_symfony
Unit tests in_symfony
 
Telerik this is sayed
Telerik this is sayedTelerik this is sayed
Telerik this is sayed
 
System analysis and_design
System analysis and_designSystem analysis and_design
System analysis and_design
 
Symfony 2
Symfony 2Symfony 2
Symfony 2
 
Story telling and_narrative
Story telling and_narrativeStory telling and_narrative
Story telling and_narrative
 

Recently uploaded

9 CEO's who hit $100m ARR Share Their Top Growth Tactics Nathan Latka, Founde...
9 CEO's who hit $100m ARR Share Their Top Growth Tactics Nathan Latka, Founde...9 CEO's who hit $100m ARR Share Their Top Growth Tactics Nathan Latka, Founde...
9 CEO's who hit $100m ARR Share Their Top Growth Tactics Nathan Latka, Founde...
saastr
 
Main news related to the CCS TSI 2023 (2023/1695)
Main news related to the CCS TSI 2023 (2023/1695)Main news related to the CCS TSI 2023 (2023/1695)
Main news related to the CCS TSI 2023 (2023/1695)
Jakub Marek
 
How to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdf
How to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdfHow to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdf
How to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdf
Chart Kalyan
 
June Patch Tuesday
June Patch TuesdayJune Patch Tuesday
June Patch Tuesday
Ivanti
 
Monitoring and Managing Anomaly Detection on OpenShift.pdf
Monitoring and Managing Anomaly Detection on OpenShift.pdfMonitoring and Managing Anomaly Detection on OpenShift.pdf
Monitoring and Managing Anomaly Detection on OpenShift.pdf
Tosin Akinosho
 
Introduction of Cybersecurity with OSS at Code Europe 2024
Introduction of Cybersecurity with OSS  at Code Europe 2024Introduction of Cybersecurity with OSS  at Code Europe 2024
Introduction of Cybersecurity with OSS at Code Europe 2024
Hiroshi SHIBATA
 
Programming Foundation Models with DSPy - Meetup Slides
Programming Foundation Models with DSPy - Meetup SlidesProgramming Foundation Models with DSPy - Meetup Slides
Programming Foundation Models with DSPy - Meetup Slides
Zilliz
 
“How Axelera AI Uses Digital Compute-in-memory to Deliver Fast and Energy-eff...
“How Axelera AI Uses Digital Compute-in-memory to Deliver Fast and Energy-eff...“How Axelera AI Uses Digital Compute-in-memory to Deliver Fast and Energy-eff...
“How Axelera AI Uses Digital Compute-in-memory to Deliver Fast and Energy-eff...
Edge AI and Vision Alliance
 
GNSS spoofing via SDR (Criptored Talks 2024)
GNSS spoofing via SDR (Criptored Talks 2024)GNSS spoofing via SDR (Criptored Talks 2024)
GNSS spoofing via SDR (Criptored Talks 2024)
Javier Junquera
 
Astute Business Solutions | Oracle Cloud Partner |
Astute Business Solutions | Oracle Cloud Partner |Astute Business Solutions | Oracle Cloud Partner |
Astute Business Solutions | Oracle Cloud Partner |
AstuteBusiness
 
"Frontline Battles with DDoS: Best practices and Lessons Learned", Igor Ivaniuk
"Frontline Battles with DDoS: Best practices and Lessons Learned",  Igor Ivaniuk"Frontline Battles with DDoS: Best practices and Lessons Learned",  Igor Ivaniuk
"Frontline Battles with DDoS: Best practices and Lessons Learned", Igor Ivaniuk
Fwdays
 
Dandelion Hashtable: beyond billion requests per second on a commodity server
Dandelion Hashtable: beyond billion requests per second on a commodity serverDandelion Hashtable: beyond billion requests per second on a commodity server
Dandelion Hashtable: beyond billion requests per second on a commodity server
Antonios Katsarakis
 
Digital Banking in the Cloud: How Citizens Bank Unlocked Their Mainframe
Digital Banking in the Cloud: How Citizens Bank Unlocked Their MainframeDigital Banking in the Cloud: How Citizens Bank Unlocked Their Mainframe
Digital Banking in the Cloud: How Citizens Bank Unlocked Their Mainframe
Precisely
 
Columbus Data & Analytics Wednesdays - June 2024
Columbus Data & Analytics Wednesdays - June 2024Columbus Data & Analytics Wednesdays - June 2024
Columbus Data & Analytics Wednesdays - June 2024
Jason Packer
 
Energy Efficient Video Encoding for Cloud and Edge Computing Instances
Energy Efficient Video Encoding for Cloud and Edge Computing InstancesEnergy Efficient Video Encoding for Cloud and Edge Computing Instances
Energy Efficient Video Encoding for Cloud and Edge Computing Instances
Alpen-Adria-Universität
 
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAU
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAUHCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAU
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAU
panagenda
 
Apps Break Data
Apps Break DataApps Break Data
Apps Break Data
Ivo Velitchkov
 
“Temporal Event Neural Networks: A More Efficient Alternative to the Transfor...
“Temporal Event Neural Networks: A More Efficient Alternative to the Transfor...“Temporal Event Neural Networks: A More Efficient Alternative to the Transfor...
“Temporal Event Neural Networks: A More Efficient Alternative to the Transfor...
Edge AI and Vision Alliance
 
Skybuffer SAM4U tool for SAP license adoption
Skybuffer SAM4U tool for SAP license adoptionSkybuffer SAM4U tool for SAP license adoption
Skybuffer SAM4U tool for SAP license adoption
Tatiana Kojar
 
Choosing The Best AWS Service For Your Website + API.pptx
Choosing The Best AWS Service For Your Website + API.pptxChoosing The Best AWS Service For Your Website + API.pptx
Choosing The Best AWS Service For Your Website + API.pptx
Brandon Minnick, MBA
 

Recently uploaded (20)

9 CEO's who hit $100m ARR Share Their Top Growth Tactics Nathan Latka, Founde...
9 CEO's who hit $100m ARR Share Their Top Growth Tactics Nathan Latka, Founde...9 CEO's who hit $100m ARR Share Their Top Growth Tactics Nathan Latka, Founde...
9 CEO's who hit $100m ARR Share Their Top Growth Tactics Nathan Latka, Founde...
 
Main news related to the CCS TSI 2023 (2023/1695)
Main news related to the CCS TSI 2023 (2023/1695)Main news related to the CCS TSI 2023 (2023/1695)
Main news related to the CCS TSI 2023 (2023/1695)
 
How to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdf
How to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdfHow to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdf
How to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdf
 
June Patch Tuesday
June Patch TuesdayJune Patch Tuesday
June Patch Tuesday
 
Monitoring and Managing Anomaly Detection on OpenShift.pdf
Monitoring and Managing Anomaly Detection on OpenShift.pdfMonitoring and Managing Anomaly Detection on OpenShift.pdf
Monitoring and Managing Anomaly Detection on OpenShift.pdf
 
Introduction of Cybersecurity with OSS at Code Europe 2024
Introduction of Cybersecurity with OSS  at Code Europe 2024Introduction of Cybersecurity with OSS  at Code Europe 2024
Introduction of Cybersecurity with OSS at Code Europe 2024
 
Programming Foundation Models with DSPy - Meetup Slides
Programming Foundation Models with DSPy - Meetup SlidesProgramming Foundation Models with DSPy - Meetup Slides
Programming Foundation Models with DSPy - Meetup Slides
 
“How Axelera AI Uses Digital Compute-in-memory to Deliver Fast and Energy-eff...
“How Axelera AI Uses Digital Compute-in-memory to Deliver Fast and Energy-eff...“How Axelera AI Uses Digital Compute-in-memory to Deliver Fast and Energy-eff...
“How Axelera AI Uses Digital Compute-in-memory to Deliver Fast and Energy-eff...
 
GNSS spoofing via SDR (Criptored Talks 2024)
GNSS spoofing via SDR (Criptored Talks 2024)GNSS spoofing via SDR (Criptored Talks 2024)
GNSS spoofing via SDR (Criptored Talks 2024)
 
Astute Business Solutions | Oracle Cloud Partner |
Astute Business Solutions | Oracle Cloud Partner |Astute Business Solutions | Oracle Cloud Partner |
Astute Business Solutions | Oracle Cloud Partner |
 
"Frontline Battles with DDoS: Best practices and Lessons Learned", Igor Ivaniuk
"Frontline Battles with DDoS: Best practices and Lessons Learned",  Igor Ivaniuk"Frontline Battles with DDoS: Best practices and Lessons Learned",  Igor Ivaniuk
"Frontline Battles with DDoS: Best practices and Lessons Learned", Igor Ivaniuk
 
Dandelion Hashtable: beyond billion requests per second on a commodity server
Dandelion Hashtable: beyond billion requests per second on a commodity serverDandelion Hashtable: beyond billion requests per second on a commodity server
Dandelion Hashtable: beyond billion requests per second on a commodity server
 
Digital Banking in the Cloud: How Citizens Bank Unlocked Their Mainframe
Digital Banking in the Cloud: How Citizens Bank Unlocked Their MainframeDigital Banking in the Cloud: How Citizens Bank Unlocked Their Mainframe
Digital Banking in the Cloud: How Citizens Bank Unlocked Their Mainframe
 
Columbus Data & Analytics Wednesdays - June 2024
Columbus Data & Analytics Wednesdays - June 2024Columbus Data & Analytics Wednesdays - June 2024
Columbus Data & Analytics Wednesdays - June 2024
 
Energy Efficient Video Encoding for Cloud and Edge Computing Instances
Energy Efficient Video Encoding for Cloud and Edge Computing InstancesEnergy Efficient Video Encoding for Cloud and Edge Computing Instances
Energy Efficient Video Encoding for Cloud and Edge Computing Instances
 
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAU
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAUHCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAU
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAU
 
Apps Break Data
Apps Break DataApps Break Data
Apps Break Data
 
“Temporal Event Neural Networks: A More Efficient Alternative to the Transfor...
“Temporal Event Neural Networks: A More Efficient Alternative to the Transfor...“Temporal Event Neural Networks: A More Efficient Alternative to the Transfor...
“Temporal Event Neural Networks: A More Efficient Alternative to the Transfor...
 
Skybuffer SAM4U tool for SAP license adoption
Skybuffer SAM4U tool for SAP license adoptionSkybuffer SAM4U tool for SAP license adoption
Skybuffer SAM4U tool for SAP license adoption
 
Choosing The Best AWS Service For Your Website + API.pptx
Choosing The Best AWS Service For Your Website + API.pptxChoosing The Best AWS Service For Your Website + API.pptx
Choosing The Best AWS Service For Your Website + API.pptx
 

Laravel

  • 1. LARAVEL FRAMEWORK DB OPERATIONS ELOQUENT MODEL Sayed Ahmed Computer Engineering, BUET, Bangladesh (Graduated on 2001) MSc., Computer Science, Canada http://www.justetc.net
  • 2. INSTALLING  You can install by using Composer  http://getcomposer.org/doc/00-intro.md
  • 3. DB STUFF  How and where to configure  app/config/database.php  Supported Databases  MySQL, Postgres, SQLite, and SQL Server  Running A Select Query  $results = DB::select('select * from users where id = ?', array(1));  Running An Insert Statement  DB::insert('insert into users (id, name) values (?, ?)', array(1, 'Dayle'));
  • 4. DB STUFF  Running An Update Statement  DB::update('update users set votes = 100 where name = ?', array('John'));  Running A General Statement  DB::statement('drop table users');  Listening For Query Events  DB::listen(function($sql, $bindings, $time) { // });
  • 5. DB STUFF  Database transactions  DB::transaction(function() {  DB::table('users')->update(array('votes' => 1));  DB::table('posts')->delete();  })  Access Connections  $users = DB::connection('foo')->select(...);  Access raw PDO instance  $pdo = DB::connection()->getPdo()  Reconnect  DB::reconnect('foo');
  • 6. DB STUFF  Query Logging  DB::connection()->disableQueryLog();  $queries = DB::getQueryLog();  Note: QueryLogging is enabled by default
  • 7. QUERY BUILDER  Select : All Rows  $users = DB::table('users')->get();  foreach ($users as $user) {  var_dump($user->name);  }  Single Row  $user = DB::table('users')->where('name', 'John')->first();  var_dump($user->name);
  • 8. QUERY BUILDER  Single column from a row  $name = DB::table('users')->where('name', 'John')- >pluck('name');  A List Of Column Values  $roles = DB::table('roles')->lists('title');  $roles = DB::table('roles')->lists('title', 'name');  $users = DB::table('users')->select('name', 'email')- >get();  $users = DB::table('users')->distinct()->get();  -$users = DB::table('users')->select('name as user_name')->get();
  • 9. QUERY BUILDER  Where  $users = DB::table('users')->where('votes', '>', 100)->get();  $users = DB::table('users') ->where('votes', '>', 100) ->orWhere('name', 'John') ->get();  Order by, group by  $users = DB::table('users') ->orderBy('name', 'desc') ->groupBy('count') ->having('count', '>', 100) ->get();
  • 10. QUERY BUILDER  Offset and limit  $users = DB::table('users')->skip(10)->take(5)- >get();
  • 11. JOINS  Basic  DB::table('users') ->join('contacts', 'users.id', '=', 'contacts.user_id') ->join('orders', 'users.id', '=', 'orders.user_id') ->select('users.id', 'contacts.phone', 'orders.price');  Left  DB::table('users') ->leftJoin('posts', 'users.id', '=', 'posts.user_id') ->get();
  • 12. JOINS  Complex  DB::table('users') ->join('contacts', function($join) { $join->on('users.id', '=', 'contacts.user_id')- >orOn(...);  }) ->get();
  • 13. OTHERS  Advanced whereas  DB::table('users') ->where('name', '=', 'John') - >orWhere(function($query) { $query- >where('votes', '>', 100) ->where('title', '<>', 'Admin'); }) ->get();  Exists  DB::table('users') ->whereExists(function($query) { $query->select(DB::raw(1)) ->from('orders') - >whereRaw('orders.user_id = users.id'); }) - >get();
  • 14. AGGREGATE METHODS  $users = DB::table('users')->count();  $price = DB::table('orders')->max('price');  $price = DB::table('orders')->min('price');  $price = DB::table('orders')->avg('price');  $total = DB::table('users')->sum('votes');
  • 15. QUERY BUILDERS  Raw Expressions  $users = DB::table('users')  ->select(DB::raw('count(*) as user_count, status'))  ->where('status', '<>', 1) ->groupBy('status') - >get();
  • 16. INCREMENT/DECREMENT  DB::table('users')->increment('votes');  DB::table('users')->increment('votes', 5);  DB::table('users')->decrement('votes');  DB::table('users')->decrement('votes', 5);  DB::table('users')->increment('votes', 1, array('name' => 'John'));
  • 17. INSERTS  Inserting Records into a table  DB::table('users')->insert( array('email' => 'john@example.com', 'votes' => 0) );  $id = DB::table('users')->insertGetId( array('email' => 'john@example.com', 'votes' => 0) );  DB::table('users')->insert(array( array('email' => 'taylor@example.com', 'votes' => 0), array('email' => 'dayle@example.com', 'votes' => 0), ));
  • 18. UPDATES  DB::table('users') ->where('id', 1) - >update(array('votes' => 1));  Deletes  DB::table('users')->where('votes', '<', 100)- >delete();  DB::table('users')->delete();  DB::table('users')->truncate();
  • 19. UNIONS  $first = DB::table('users')  ->whereNull('first_name');  $users = DB::table('users')  ->whereNull('last_name')->union($first)->get();  Caching Results  $users = DB::table('users')->remember(10)- >get();  Remember for 10 minutes
  • 20. ELOQUENT ORM  The Eloquent ORM included with Laravel provides a beautiful, simple ActiveRecord implementation for working with your database. Each database table has a corresponding "Model" which is used to interact with that table.
  • 21. ELOQUENT MODEL  Defining An Eloquent Model  class User extends Eloquent {}  By default it will point to the table users  Lowercase and plural form  class User extends Eloquent {  protected $table = 'my_users';  }  Note: you can use properties such as primaryKey and connection  All table should have createdat and updatedat columns else use $timestamps = false in the model
  • 22. ELOQUENT MODEL AND DB OPERATIONS  Retrieve All  $users = User::all();  Retrieve by Primary key  $user = User::find(1);  var_dump($user->name);  Retrieve or Throw exception  $model = User::findOrFail(1); $model = User::where('votes', '>', 100)->firstOrFail();
  • 23. HANDLING EXCEPTIONS  Handling Exceptions  use IlluminateDatabaseEloquentModelNotFoundEx ception; App::error(function(ModelNotFoundException $e) { return Response::make('Not Found', 404); });
  • 24. QUERYING  Querying  $users = User::where('votes', '>', 100)->take(10)- >get(); foreach ($users as $user) { var_dump($user->name); }  Aggregates  $count = User::where('votes', '>', 100)->count();  $users = User::whereRaw('age > ? and votes = 100', array(25))->get();  Connection to use  $user = User::on('connection-name')->find(1);
  • 25. FILLABLE  The fillable property specifies which attributes should be mass-assignable. This can be set at the class or instance level.  class User extends Eloquent {  protected $fillable = array('first_name', 'last_name', 'email'); }  Guarded (not mass assignable)  class User extends Eloquent {  protected $guarded = array('id', 'password');  }
  • 26. BLOCKING AND INSERTION  Block all attributes from mass assignment  protected $guarded = array('*');  Insert a new row  $user = new User;  $user->name = 'John';  $user->save();
  • 27. UPDATE A ROW  $user = User::create(array('name' => 'John'));  Updating a retrieved model  $user = User::find(1); $user->email = 'john@foo.com'; $user->save();
  • 28. SOME SAVE, UPDATE, DELETE STUFF  Saving a model and relationship  $user->push();  Updates as queries  $affectedRows = User::where('votes', '>', 100)  ->update(array('status' => 2));  Delete by key  User::destroy(1);  User::destroy(array(1, 2, 3));  User::destroy(1, 2, 3);
  • 29.  Updating Model’s Timestamp  $user->touch();  Soft Delete  class User extends Eloquent { protected $softDelete = true; }  $table->softDeletes();  Soft deleted stuff into results (trashed + untrashed)  $table->softDeletes();  Only Trashed  $users = User::onlyTrashed()->where('account_id', 1)- >get();
  • 30.  Restore softdeleted into active  $user->restore();  On query  User::withTrashed()->where('account_id', 1)- >restore();  On relationships  $user->posts()->restore();
  • 32. QUERY SCOPES  Like variable Scope  Define query scope  class User extends Eloquent {  public function scopePopular($query) {  return $query->where('votes', '>', 100);  }  public function scopeWomen($query) {  return $query->whereGender('W');  }  }
  • 33.  Utilize Query Scopes  $users = User::popular()->women()- >orderBy('created_at')->get();  Dynamic Scopes  class User extends Eloquent {  public function scopeOfType($query, $type) {  return $query->whereType($type);  }  }
  • 34.  $users = User::ofType('member')->get();
  • 35. RELATIONSHIPS  One To One  One To Many  Many To Many  Polymorphic Relations
  • 36. DEFINE ONE TO ONE  class User extends Eloquent {  public function phone() {  return $this->hasOne('Phone');  }  }  Use  $phone = User::find(1)->phone;
  • 37. INVERSE OF A RELATION  class Phone extends Eloquent {  public function user() {  return $this->belongsTo('User');  }  }  class Phone extends Eloquent {  public function user() {  return $this->belongsTo('User', 'custom_key');  }  }`
  • 38.  class Phone extends Eloquent {  public function user() {  return $this->belongsTo('User', 'custom_key');  }  }
  • 39. ONE TO MANY  class Post extends Eloquent {  public function comments() {  return $this->hasMany('Comment');  }  }  return $this->hasMany('Comment', 'custom_key');  $comments = Post::find(1)->comments;  $comments = Post::find(1)->comments()  ->where('title', '=', 'foo')->first();
  • 40. INVERSE OF A RELATION  class Comment extends Eloquent {  public function post() {  return $this->belongsTo('Post');  }  }
  • 41. MANY TO MANY  class User extends Eloquent {  public function roles() {  return $this->belongsToMany('Role');  }  }  return $this->belongsToMany('Role', 'user_roles');  return $this->belongsToMany('Role', 'user_roles', 'user_id', 'foo_id');  $roles = User::find(1)->roles;
  • 42. INVERSE OF A RELATION  class Role extends Eloquent {  public function users() {  return $this->belongsToMany('User');  }  }
  • 43. POLYMORPHIC RELATIONS  Polymorphic relations allow a model to belong to more than one other model, on a single association.
  • 44.  class Photo extends Eloquent { public function imageable() { return $this- >morphTo(); } } class Staff extends Eloquent { public function photos() { return $this- >morphMany('Photo', 'imageable'); } } class Order extends Eloquent { public function photos() { return $this->morphMany('Photo', 'imageable'); } }
  • 45. USE  $staff = Staff::find(1); foreach ($staff->photos as $photo) { // }  $photo = Photo::find(1);  $imageable = $photo->imageable;
  • 46. QUERYING RELATIONS  $posts = Post::has('comments')->get()  $posts = Post::has('comments', '>=', 3)- >get();
  • 47. DYNAMIC PROPERTIES  Eloquent allows you to access your relations via dynamic properties. Eloquent will automatically load the relationship for you, and is even smart enough to know whether to call the get (for one-to-many relationships) or first (for one-to-one relationships) method
  • 48. EAGER LOADING  Will hit db 26 times for 25 books  foreach (Book::all() as $book) { echo $book- >author->name; }  Is reduced to two queries  foreach (Book::with('author')->get() as $book) { echo $book->author->name; }  select * from books select * from authors where id in (1, 2, 3, 4, 5, ...)
  • 49.  With constraints  $users = User::with(array('posts' => function($query) { $query->where('title', 'like', '%first%'); }))->get();
  • 50. MUST SEE  http://codehappy.daylerees.com/eloquent- orm  http://net.tutsplus.com/tutorials/php/build- web-apps-from-scratch-with-laravel-the- eloquent-orm/