SlideShare ist ein Scribd-Unternehmen logo
1 von 50
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/

Weitere ähnliche Inhalte

Was ist angesagt?

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
 
Database API, your new friend
Database API, your new friendDatabase API, your new friend
Database API, your new friend
kikoalonsob
 
DrupalCamp Foz - Novas APIs Drupal 7
DrupalCamp Foz - Novas APIs Drupal 7DrupalCamp Foz - Novas APIs Drupal 7
DrupalCamp Foz - Novas APIs Drupal 7
chuvainc
 
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
 

Was ist angesagt? (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
 

Ähnlich wie Laravel

Mocking Dependencies in PHPUnit
Mocking Dependencies in PHPUnitMocking Dependencies in PHPUnit
Mocking Dependencies in PHPUnit
mfrost503
 

Ähnlich wie 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
 

Mehr von Sayed Ahmed

Mehr von 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
 

Kürzlich hochgeladen

Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
vu2urc
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
Earley Information Science
 

Kürzlich hochgeladen (20)

🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your Business
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.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/