SlideShare a Scribd company logo
Object-Oriented
Programming
(with Laravel)
By: Shahrzad Peyman
Session 6
May-2017
shahrzad.peymaan@gmail.com
1
2
Today’s Presentation
• DataBase:Migrations
• DataBase:Seeding
• Eloquent (Getting Start)
3
DataBase:Migrations
Migrations are like version control for your database,
allowing your team to easily modify and share the
application's database schema.
Migrations are typically paired with Laravel's schema
builder to easily build your application's database
schema. If you have ever had to tell a teammate to
manually add a column to their local database
schema, you've faced the problem that database
migrations solve.
Generating Migrations
4
To create a migration, use the make:migration
Artisan command:
The new migration will be placed in your database/migrations
directory. Each migration file name contains a timestamp
which allows Laravel to determine the order of the migrations.
5
The --table and --create options may also be used to
indicate the name of the table and whether the
migration will be creating a new table. These options
simply pre-fill the generated migration stub file with
the specified table.
Generating Migrations
6
Migration Structure
A migration class
contains two methods:
up and down. The up
method is used to add
new tables, columns,
or indexes to your
database, while the
down method should
simply reverse the
operations performed
by the up method.
Running Migrations
7
To run all of your outstanding migrations, execute
the migrate Artisan command:
8
Rollback & Migrate In Single Command
The migrate:refresh command will roll back all of your
migrations and then execute the migrate command. This
command effectively re-creates your entire database:
Running Migrations
Create Table
9
To create a new database table, use the create
method on the Schema facade. The create
method accepts two arguments. The first is the
name of the table, while the second is a Closure
which receives a BluePrint object that may be
used to define the new table:
Tables
10
Renaming / Dropping Tables
11
Columns
Of course, when creating the table, you may use
any of the schema builder's column methods to
define the table's columns.
12
Available Column Types
13
Column Modifiers
14
15
Before modifying a column, be sure to add the doctrine/dbal
dependency to your composer.json file. The Doctrine DBAL
library is used to determine the current state of the column
and create the SQL queries needed to make the specified
adjustments to the column:
Modifying Columns
16
Modifying Columns
The change method allows you to modify some existing
column types to a new type or modify the column's
attributes. For example, you may wish to increase the size of
a string column. To see the change method in action, let's
increase the size of the name column from 25 to 50:
Rename/Drop Column
17
Before renaming a column, be sure to add the doctrine/dbal
dependency to your composer.json file.
Indexes
18
The schema builder supports several types of indexes. First,
let's look at an example that specifies a column's values
should be unique. To create the index, we can simply chain
the unique method onto the column definition:
19
Indexes
You may even pass an array of columns to an index
method to create a compound index.
Laravel will automatically generate a reasonable
index name, but you may pass a second argument
to the method to specify the name yourself.
20
Foreign Key Constraints
Laravel also provides support for creating foreign key
constraints, which are used to force referential
integrity at the database level. For example, let's
define a user_id column on the posts table that
references the id column on a users table:
21
Drop Foreign Key
To drop a foreign key, you may use the
dropForeign method. Foreign key constraints use
the same naming convention as indexes. So, we
will concatenate the table name and the columns in
the constraint then suffix the name with "_foreign":
22
Database:Seeding
Laravel includes a simple method of seeding your
database with test data using seed classes. All seed
classes are stored in the database/seeds directory.
Seed classes may have any name you wish, but
probably should follow some sensible convention,
such as UserTableSeeder, etc. By default, a
databaseSeeder class is defined for you. From this
class, you may use the call method to run other seed
classes, allowing you to control the seeding order.
Writing Seeders
23
To generate a seeder,
execute the make:seeder
Artisan command. All
seeders generated by the
framework will be placed
in the database/seeds
directory. A seeder class
only contains one method
by default: run. This
method is called when the
db:seed Artisan command
is executed. Within the run
method, you may insert
data into your database
however you wish.
24
Calling Additional Seeder
24
25
Running Seeders
Once you have written your seeder classes, you may use the
db:seed Artisan command to seed your database. By default,
the db:seed command runs the DatabaseSeeder class, which
may be used to call other seed classes. However, you may
use the --class option to specify a specific seeder class to
run individually:
25
26
Eloquent
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. Models allow you to query
for data in your tables, as well as insert new
records into the table.
Before getting started, be sure to configure a
database connection in config/database.php.
27
Defining Models
To get started, let's create an Eloquent
model. Models typically live in the app
directory, but you are free to place them
anywhere.
A l l E l o q u e n t m o d e l s e x t e n d
IlluminateDatabaseEloquentModel
class.
28
Eloquent Model Conventions
Now, let's look at an example Flight model,
which we will use to retrieve and store
information from our flights database table:
29
Table Names
Note that we did not tell Eloquent
which table to use for our Flight
model. By convention, the "snake
case", plural name of the class
will be used as the table name
unless another name is explicitly
specified. So, in this case,
Eloquent will assume the Flight
model stores records in the
flights table. You may specify a
custom table by defining a table
property on your model:
30
Primary Key
Eloquent will also assume that each table has a
primary key column named id. You may define a
$primaryKey property to override this convention. In
addition, Eloquent assumes that the primary key is
an incrementing integer value, which means that by
default the primary key will be cast to an int
automatically. If you wish to use a non-incrementing
or a non-numeric primary key you must set the public
$incrementing property on your model to false.
31
TimeStamps
B y d e f a u l t , E l o q u e n t
expects created_at and
updated_at columns to
exist on your tables. If you
do not wish to have these
columns automatically
managed by Eloquent, set
the $timestamps property
on your model to false:
32
TimeStamps
Database Connection
33
Retrieving Models
34
Once you have created
a m o d e l a n d i t s
associated database
table, you are ready to
start retrieving data
from your database.
Think of each Eloquent
model as a powerful
query builder allowing
you to fluently query
the database table
associated with the
model. For example:
35
Chunk
If you need to process thousands of Eloquent records, use
the chunk command. The chunk method will retrieve a
"chunk" of Eloquent models, feeding them to a given
Closure for processing. Using the chunk method will
conserve memory when working with large result sets:
36
Cursor
The cursor method allows you to iterate through your
database records using a cursor, which will only execute a
single query. When processing large amounts of data, the
cursor method may be used to greatly reduce your memory
usage:
37
Retrieving Single Models / Aggregates
38
Inserting & Updating Models
39
Mass Updates
40
Mass Assignment
41
Guarding Attributes
42
UpdateOrCreate
You may also come across situations where you want to
update an existing model or create a new model if none
exists. Laravel provides an updateOrCreate method to do
this in one step. This Method persists the model, so there's
no need to call save():
43
Deleting Models

More Related Content

PDF
Object Oriented Programming with Laravel - Session 4
PDF
Object Oriented Programming with Laravel - Session 5
PDF
Object Oriented Programming with Laravel - Session 2
PPTX
Sql Injection attacks and prevention
PPT
Entity frameworks101
PPTX
Web application penetration using SQLMAP.
PDF
Oracle Concurrent Program Setup document
PPTX
Object Oriented Programming with Laravel - Session 4
Object Oriented Programming with Laravel - Session 5
Object Oriented Programming with Laravel - Session 2
Sql Injection attacks and prevention
Entity frameworks101
Web application penetration using SQLMAP.
Oracle Concurrent Program Setup document

What's hot (18)

PPTX
PPTX
Php and web forms
PPT
SQL Injection Attacks
PDF
SQL Injection Attack Detection and Prevention Techniques to Secure Web-Site
PPTX
Instant DBMS Homework Help
PPT
Rail3 intro 29th_sep_surendran
PDF
Impala SQL Support
PPT
Sql injection attacks
PPTX
ApacheCon North America 2018: Creating Spark Data Sources
DOCX
Hyperion Essbase integration with ODI
PPTX
cakephp UDUYKTHA (1)
PPTX
Sql injection
PPT
Rails
 
PPT
D:\Technical\Ppt\Sql Injection
PPTX
Using SP Metal for faster share point development
PDF
Poster Declaratively Describing Responses of Hypermedia-Driven Web APIs
PPT
SQL Injection
PPTX
Using SPMetal for faster SharePoint development
Php and web forms
SQL Injection Attacks
SQL Injection Attack Detection and Prevention Techniques to Secure Web-Site
Instant DBMS Homework Help
Rail3 intro 29th_sep_surendran
Impala SQL Support
Sql injection attacks
ApacheCon North America 2018: Creating Spark Data Sources
Hyperion Essbase integration with ODI
cakephp UDUYKTHA (1)
Sql injection
Rails
 
D:\Technical\Ppt\Sql Injection
Using SP Metal for faster share point development
Poster Declaratively Describing Responses of Hypermedia-Driven Web APIs
SQL Injection
Using SPMetal for faster SharePoint development
Ad

Similar to Object Oriented Programming with Laravel - Session 6 (20)

PPTX
Getting Started with MySQL I
PPTX
7. SQL.pptx
PPTX
Schema webinar
PPTX
PPTX
3-Chapter-Edit.pptx debre tabour university
DOCX
Assignment # 2PreliminariesImportant Points· Evidence of acad.docx
PPT
Synapseindia dot net development chapter 8 asp dot net
PPTX
Database COMPLETE
PPTX
Chapter 3.pptx Oracle SQL or local Android database setup SQL, SQL-Lite, codi...
PPT
My sql with querys
PDF
lab56_db
PDF
lab56_db
DOCX
Android database tutorial
ODP
Sql lite android
PDF
Mysql Datadictionary
PDF
Copy Of Mysql Datadictionary
DOCX
MCS,BCS-7(A,B) Visual programming Syllabus for Final exams @ ISP
PDF
Persistence in Android
DOC
Setting And Changing The Column Collation.Doc
Getting Started with MySQL I
7. SQL.pptx
Schema webinar
3-Chapter-Edit.pptx debre tabour university
Assignment # 2PreliminariesImportant Points· Evidence of acad.docx
Synapseindia dot net development chapter 8 asp dot net
Database COMPLETE
Chapter 3.pptx Oracle SQL or local Android database setup SQL, SQL-Lite, codi...
My sql with querys
lab56_db
lab56_db
Android database tutorial
Sql lite android
Mysql Datadictionary
Copy Of Mysql Datadictionary
MCS,BCS-7(A,B) Visual programming Syllabus for Final exams @ ISP
Persistence in Android
Setting And Changing The Column Collation.Doc
Ad

More from Shahrzad Peyman (10)

PDF
Web Design & Development - Session 9
PDF
Web Design & Development - Session 8
PDF
Web Design & Development - Session 7
PDF
Web Design & Development - Session 6
PDF
Web Design & Development - Session 4
PDF
Web Design & Development - Session 3
PDF
Web Design & Development - Session 2
PDF
Web Design & Development - Session 1
PDF
Object Oriented Programming with Laravel - Session 3
PDF
Object Oriented Programming with Laravel - Session 1
Web Design & Development - Session 9
Web Design & Development - Session 8
Web Design & Development - Session 7
Web Design & Development - Session 6
Web Design & Development - Session 4
Web Design & Development - Session 3
Web Design & Development - Session 2
Web Design & Development - Session 1
Object Oriented Programming with Laravel - Session 3
Object Oriented Programming with Laravel - Session 1

Recently uploaded (20)

PDF
System and Network Administration Chapter 2
PPTX
What to Capture When It Breaks: 16 Artifacts That Reveal Root Causes
PDF
The Role of Automation and AI in EHS Management for Data Centers.pdf
PDF
AI in Product Development-omnex systems
PDF
Convert Thunderbird to Outlook into bulk
PPTX
Presentation of Computer CLASS 2 .pptx
PDF
Teaching Reproducibility and Embracing Variability: From Floating-Point Exper...
PDF
QAware_Mario-Leander_Reimer_Architecting and Building a K8s-based AI Platform...
PDF
Claude Code: Everyone is a 10x Developer - A Comprehensive AI-Powered CLI Tool
PDF
How to Confidently Manage Project Budgets
PDF
How to Choose the Most Effective Social Media Agency in Bangalore.pdf
PPTX
Benefits of DCCM for Genesys Contact Center
PPT
JAVA ppt tutorial basics to learn java programming
PDF
Best Practices for Rolling Out Competency Management Software.pdf
PDF
Flood Susceptibility Mapping Using Image-Based 2D-CNN Deep Learnin. Overview ...
PDF
Jenkins: An open-source automation server powering CI/CD Automation
PDF
Become an Agentblazer Champion Challenge Kickoff
PPTX
ManageIQ - Sprint 268 Review - Slide Deck
PDF
System and Network Administraation Chapter 3
DOCX
The Five Best AI Cover Tools in 2025.docx
System and Network Administration Chapter 2
What to Capture When It Breaks: 16 Artifacts That Reveal Root Causes
The Role of Automation and AI in EHS Management for Data Centers.pdf
AI in Product Development-omnex systems
Convert Thunderbird to Outlook into bulk
Presentation of Computer CLASS 2 .pptx
Teaching Reproducibility and Embracing Variability: From Floating-Point Exper...
QAware_Mario-Leander_Reimer_Architecting and Building a K8s-based AI Platform...
Claude Code: Everyone is a 10x Developer - A Comprehensive AI-Powered CLI Tool
How to Confidently Manage Project Budgets
How to Choose the Most Effective Social Media Agency in Bangalore.pdf
Benefits of DCCM for Genesys Contact Center
JAVA ppt tutorial basics to learn java programming
Best Practices for Rolling Out Competency Management Software.pdf
Flood Susceptibility Mapping Using Image-Based 2D-CNN Deep Learnin. Overview ...
Jenkins: An open-source automation server powering CI/CD Automation
Become an Agentblazer Champion Challenge Kickoff
ManageIQ - Sprint 268 Review - Slide Deck
System and Network Administraation Chapter 3
The Five Best AI Cover Tools in 2025.docx

Object Oriented Programming with Laravel - Session 6

  • 2. 2 Today’s Presentation • DataBase:Migrations • DataBase:Seeding • Eloquent (Getting Start)
  • 3. 3 DataBase:Migrations Migrations are like version control for your database, allowing your team to easily modify and share the application's database schema. Migrations are typically paired with Laravel's schema builder to easily build your application's database schema. If you have ever had to tell a teammate to manually add a column to their local database schema, you've faced the problem that database migrations solve.
  • 4. Generating Migrations 4 To create a migration, use the make:migration Artisan command: The new migration will be placed in your database/migrations directory. Each migration file name contains a timestamp which allows Laravel to determine the order of the migrations.
  • 5. 5 The --table and --create options may also be used to indicate the name of the table and whether the migration will be creating a new table. These options simply pre-fill the generated migration stub file with the specified table. Generating Migrations
  • 6. 6 Migration Structure A migration class contains two methods: up and down. The up method is used to add new tables, columns, or indexes to your database, while the down method should simply reverse the operations performed by the up method.
  • 7. Running Migrations 7 To run all of your outstanding migrations, execute the migrate Artisan command:
  • 8. 8 Rollback & Migrate In Single Command The migrate:refresh command will roll back all of your migrations and then execute the migrate command. This command effectively re-creates your entire database: Running Migrations
  • 9. Create Table 9 To create a new database table, use the create method on the Schema facade. The create method accepts two arguments. The first is the name of the table, while the second is a Closure which receives a BluePrint object that may be used to define the new table:
  • 11. Renaming / Dropping Tables 11
  • 12. Columns Of course, when creating the table, you may use any of the schema builder's column methods to define the table's columns. 12
  • 15. 15 Before modifying a column, be sure to add the doctrine/dbal dependency to your composer.json file. The Doctrine DBAL library is used to determine the current state of the column and create the SQL queries needed to make the specified adjustments to the column: Modifying Columns
  • 16. 16 Modifying Columns The change method allows you to modify some existing column types to a new type or modify the column's attributes. For example, you may wish to increase the size of a string column. To see the change method in action, let's increase the size of the name column from 25 to 50:
  • 17. Rename/Drop Column 17 Before renaming a column, be sure to add the doctrine/dbal dependency to your composer.json file.
  • 18. Indexes 18 The schema builder supports several types of indexes. First, let's look at an example that specifies a column's values should be unique. To create the index, we can simply chain the unique method onto the column definition:
  • 19. 19 Indexes You may even pass an array of columns to an index method to create a compound index. Laravel will automatically generate a reasonable index name, but you may pass a second argument to the method to specify the name yourself.
  • 20. 20 Foreign Key Constraints Laravel also provides support for creating foreign key constraints, which are used to force referential integrity at the database level. For example, let's define a user_id column on the posts table that references the id column on a users table:
  • 21. 21 Drop Foreign Key To drop a foreign key, you may use the dropForeign method. Foreign key constraints use the same naming convention as indexes. So, we will concatenate the table name and the columns in the constraint then suffix the name with "_foreign":
  • 22. 22 Database:Seeding Laravel includes a simple method of seeding your database with test data using seed classes. All seed classes are stored in the database/seeds directory. Seed classes may have any name you wish, but probably should follow some sensible convention, such as UserTableSeeder, etc. By default, a databaseSeeder class is defined for you. From this class, you may use the call method to run other seed classes, allowing you to control the seeding order.
  • 23. Writing Seeders 23 To generate a seeder, execute the make:seeder Artisan command. All seeders generated by the framework will be placed in the database/seeds directory. A seeder class only contains one method by default: run. This method is called when the db:seed Artisan command is executed. Within the run method, you may insert data into your database however you wish.
  • 25. 25 Running Seeders Once you have written your seeder classes, you may use the db:seed Artisan command to seed your database. By default, the db:seed command runs the DatabaseSeeder class, which may be used to call other seed classes. However, you may use the --class option to specify a specific seeder class to run individually: 25
  • 26. 26 Eloquent 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. Models allow you to query for data in your tables, as well as insert new records into the table. Before getting started, be sure to configure a database connection in config/database.php.
  • 27. 27 Defining Models To get started, let's create an Eloquent model. Models typically live in the app directory, but you are free to place them anywhere. A l l E l o q u e n t m o d e l s e x t e n d IlluminateDatabaseEloquentModel class.
  • 28. 28 Eloquent Model Conventions Now, let's look at an example Flight model, which we will use to retrieve and store information from our flights database table:
  • 29. 29 Table Names Note that we did not tell Eloquent which table to use for our Flight model. By convention, the "snake case", plural name of the class will be used as the table name unless another name is explicitly specified. So, in this case, Eloquent will assume the Flight model stores records in the flights table. You may specify a custom table by defining a table property on your model:
  • 30. 30 Primary Key Eloquent will also assume that each table has a primary key column named id. You may define a $primaryKey property to override this convention. In addition, Eloquent assumes that the primary key is an incrementing integer value, which means that by default the primary key will be cast to an int automatically. If you wish to use a non-incrementing or a non-numeric primary key you must set the public $incrementing property on your model to false.
  • 31. 31 TimeStamps B y d e f a u l t , E l o q u e n t expects created_at and updated_at columns to exist on your tables. If you do not wish to have these columns automatically managed by Eloquent, set the $timestamps property on your model to false:
  • 34. Retrieving Models 34 Once you have created a m o d e l a n d i t s associated database table, you are ready to start retrieving data from your database. Think of each Eloquent model as a powerful query builder allowing you to fluently query the database table associated with the model. For example:
  • 35. 35 Chunk If you need to process thousands of Eloquent records, use the chunk command. The chunk method will retrieve a "chunk" of Eloquent models, feeding them to a given Closure for processing. Using the chunk method will conserve memory when working with large result sets:
  • 36. 36 Cursor The cursor method allows you to iterate through your database records using a cursor, which will only execute a single query. When processing large amounts of data, the cursor method may be used to greatly reduce your memory usage:
  • 42. 42 UpdateOrCreate You may also come across situations where you want to update an existing model or create a new model if none exists. Laravel provides an updateOrCreate method to do this in one step. This Method persists the model, so there's no need to call save():