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

What's hot (18)

PPTX
Sqlmap
SiddharthWagh7
 
PPTX
Php and web forms
sana mateen
 
PPT
SQL Injection Attacks
Compare Infobase Limited
 
PDF
SQL Injection Attack Detection and Prevention Techniques to Secure Web-Site
ijtsrd
 
PPTX
Instant DBMS Homework Help
Database Homework Help
 
PPT
Rail3 intro 29th_sep_surendran
SPRITLE SOFTWARE PRIVATE LIMIT ED
 
PDF
Impala SQL Support
Yue Chen
 
PPT
Sql injection attacks
Kumar
 
PPTX
ApacheCon North America 2018: Creating Spark Data Sources
Jayesh Thakrar
 
DOCX
Hyperion Essbase integration with ODI
Dharmaraj Borse
 
PPTX
cakephp UDUYKTHA (1)
Varsha Krishna
 
PPTX
Sql injection
Hemendra Kumar
 
PPT
Rails
SHC
 
PPT
D:\Technical\Ppt\Sql Injection
avishkarm
 
PPTX
Using SP Metal for faster share point development
Pranav Sharma
 
PDF
Poster Declaratively Describing Responses of Hypermedia-Driven Web APIs
Ruben Taelman
 
PPT
SQL Injection
Adhoura Academy
 
PPTX
Using SPMetal for faster SharePoint development
Pranav Sharma
 
Php and web forms
sana mateen
 
SQL Injection Attacks
Compare Infobase Limited
 
SQL Injection Attack Detection and Prevention Techniques to Secure Web-Site
ijtsrd
 
Instant DBMS Homework Help
Database Homework Help
 
Rail3 intro 29th_sep_surendran
SPRITLE SOFTWARE PRIVATE LIMIT ED
 
Impala SQL Support
Yue Chen
 
Sql injection attacks
Kumar
 
ApacheCon North America 2018: Creating Spark Data Sources
Jayesh Thakrar
 
Hyperion Essbase integration with ODI
Dharmaraj Borse
 
cakephp UDUYKTHA (1)
Varsha Krishna
 
Sql injection
Hemendra Kumar
 
Rails
SHC
 
D:\Technical\Ppt\Sql Injection
avishkarm
 
Using SP Metal for faster share point development
Pranav Sharma
 
Poster Declaratively Describing Responses of Hypermedia-Driven Web APIs
Ruben Taelman
 
SQL Injection
Adhoura Academy
 
Using SPMetal for faster SharePoint development
Pranav Sharma
 

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

PDF
Web Programming - 8 Database, Model and Eloquent
AndiNurkholis1
 
PPTX
Introduction to laravel framework
Ahmad Fatoni
 
PDF
Getting to know Laravel 5
Bukhori Aqid
 
PDF
Laravel Level 1 (The Basic)
Kriangkrai Chaonithi
 
PDF
Best Laravel Eloquent Tips and Tricks
Techtic Solutions
 
PPTX
What-is-Laravel and introduciton to Laravel
PraveenHegde20
 
DOCX
Laravel
biplob04
 
PPTX
Laravel
Sayed Ahmed
 
PPTX
Laravel Tutorial PPT
Piyush Aggarwal
 
PDF
Laravel - Speaking eloquent eloquently
Laravel Nigeria
 
PDF
Speaking Eloquent Eloquently
Stephen Afam-Osemene
 
PPTX
Laravel - Website Development in Php Framework.
SWAAM Tech
 
PPTX
What-is-Laravel-23-August-2017.pptx
AbhijeetKumar456867
 
PDF
Laravel tips-2019-04
Fernando Andrés Pérez Alarcón
 
PPTX
Laravel ppt
Mayank Panchal
 
PDF
Web Development with Laravel 5
Soheil Khodayari
 
PPTX
CRUD presentation of laravel application.pptx
ShoukatRiaz
 
PDF
Laravel and Django and Rails, Oh My!
Chris Roberts
 
PPTX
REST APIs in Laravel 101
Samantha Geitz
 
PDF
Doctrine For Beginners
Jonathan Wage
 
Web Programming - 8 Database, Model and Eloquent
AndiNurkholis1
 
Introduction to laravel framework
Ahmad Fatoni
 
Getting to know Laravel 5
Bukhori Aqid
 
Laravel Level 1 (The Basic)
Kriangkrai Chaonithi
 
Best Laravel Eloquent Tips and Tricks
Techtic Solutions
 
What-is-Laravel and introduciton to Laravel
PraveenHegde20
 
Laravel
biplob04
 
Laravel
Sayed Ahmed
 
Laravel Tutorial PPT
Piyush Aggarwal
 
Laravel - Speaking eloquent eloquently
Laravel Nigeria
 
Speaking Eloquent Eloquently
Stephen Afam-Osemene
 
Laravel - Website Development in Php Framework.
SWAAM Tech
 
What-is-Laravel-23-August-2017.pptx
AbhijeetKumar456867
 
Laravel tips-2019-04
Fernando Andrés Pérez Alarcón
 
Laravel ppt
Mayank Panchal
 
Web Development with Laravel 5
Soheil Khodayari
 
CRUD presentation of laravel application.pptx
ShoukatRiaz
 
Laravel and Django and Rails, Oh My!
Chris Roberts
 
REST APIs in Laravel 101
Samantha Geitz
 
Doctrine For Beginners
Jonathan Wage
 
Ad

More from Shahrzad Peyman (10)

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

Recently uploaded (20)

PDF
Build It, Buy It, or Already Got It? Make Smarter Martech Decisions
bbedford2
 
PDF
유니티에서 Burst Compiler+ThreadedJobs+SIMD 적용사례
Seongdae Kim
 
PPTX
OpenChain @ OSS NA - In From the Cold: Open Source as Part of Mainstream Soft...
Shane Coughlan
 
PDF
AI + DevOps = Smart Automation with devseccops.ai.pdf
Devseccops.ai
 
PDF
How to Hire AI Developers_ Step-by-Step Guide in 2025.pdf
DianApps Technologies
 
PPTX
Comprehensive Risk Assessment Module for Smarter Risk Management
EHA Soft Solutions
 
PPTX
Agentic Automation Journey Series Day 2 – Prompt Engineering for UiPath Agents
klpathrudu
 
PPTX
AEM User Group: India Chapter Kickoff Meeting
jennaf3
 
PDF
SAP Firmaya İade ABAB Kodları - ABAB ile yazılmıl hazır kod örneği
Salih Küçük
 
PPTX
Tally software_Introduction_Presentation
AditiBansal54083
 
PDF
The 5 Reasons for IT Maintenance - Arna Softech
Arna Softech
 
PDF
MiniTool Partition Wizard 12.8 Crack License Key LATEST
hashhshs786
 
PPTX
Coefficient of Variance in IBM SPSS Statistics Version 31.pptx
Version 1 Analytics
 
PPTX
ChiSquare Procedure in IBM SPSS Statistics Version 31.pptx
Version 1 Analytics
 
PDF
Empower Your Tech Vision- Why Businesses Prefer to Hire Remote Developers fro...
logixshapers59
 
PDF
Digger Solo: Semantic search and maps for your local files
seanpedersen96
 
PPTX
Milwaukee Marketo User Group - Summer Road Trip: Mapping and Personalizing Yo...
bbedford2
 
PDF
Technical-Careers-Roadmap-in-Software-Market.pdf
Hussein Ali
 
PDF
Open Chain Q2 Steering Committee Meeting - 2025-06-25
Shane Coughlan
 
PDF
4K Video Downloader Plus Pro Crack for MacOS New Download 2025
bashirkhan333g
 
Build It, Buy It, or Already Got It? Make Smarter Martech Decisions
bbedford2
 
유니티에서 Burst Compiler+ThreadedJobs+SIMD 적용사례
Seongdae Kim
 
OpenChain @ OSS NA - In From the Cold: Open Source as Part of Mainstream Soft...
Shane Coughlan
 
AI + DevOps = Smart Automation with devseccops.ai.pdf
Devseccops.ai
 
How to Hire AI Developers_ Step-by-Step Guide in 2025.pdf
DianApps Technologies
 
Comprehensive Risk Assessment Module for Smarter Risk Management
EHA Soft Solutions
 
Agentic Automation Journey Series Day 2 – Prompt Engineering for UiPath Agents
klpathrudu
 
AEM User Group: India Chapter Kickoff Meeting
jennaf3
 
SAP Firmaya İade ABAB Kodları - ABAB ile yazılmıl hazır kod örneği
Salih Küçük
 
Tally software_Introduction_Presentation
AditiBansal54083
 
The 5 Reasons for IT Maintenance - Arna Softech
Arna Softech
 
MiniTool Partition Wizard 12.8 Crack License Key LATEST
hashhshs786
 
Coefficient of Variance in IBM SPSS Statistics Version 31.pptx
Version 1 Analytics
 
ChiSquare Procedure in IBM SPSS Statistics Version 31.pptx
Version 1 Analytics
 
Empower Your Tech Vision- Why Businesses Prefer to Hire Remote Developers fro...
logixshapers59
 
Digger Solo: Semantic search and maps for your local files
seanpedersen96
 
Milwaukee Marketo User Group - Summer Road Trip: Mapping and Personalizing Yo...
bbedford2
 
Technical-Careers-Roadmap-in-Software-Market.pdf
Hussein Ali
 
Open Chain Q2 Steering Committee Meeting - 2025-06-25
Shane Coughlan
 
4K Video Downloader Plus Pro Crack for MacOS New Download 2025
bashirkhan333g
 

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():