-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathChapter 5
232 lines (185 loc) · 5.65 KB
/
Chapter 5
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
Database configuration file:
- configure/database.php
You select a specific connection with:
- DB::connection("secondary")->select("select * from users");
Migration:
- migration is a snigle file to define the modificatoins up and down
- make migration:
= php artisan make:migration create_name_table
= optional flag: --table=table_name for modifying
= optional flag: --create=table_name for creating
Creating Tables:
- method create(table_name, closure to define columns)
- pass the $table as a Blue print instance, it has the methods
Columns types:
- integer, tinyInteger, smallInteger, mediumInteger, bigInteger
- string
- boolean
- binary: BLOB
- decimal
- double
- float
- char
- datetime
- enum
- json, jsonb
- text
- time
- timestamp
- uuid
Special Columns:
- Increments, bigIncrements
- timestamps: created_at, updated_at
- remeberToken
- softDelete
- morphs
Extra properties:
- nullable
- after
- first
- last
- default
- unique
- primary
- index
- unsigned
Drop:
- dropIfExists("table_name")
Modifying columns:
- same as creating then ->change()
- renameColumn(): to rename
- dropColumn(): to drop
Indexes and foreign keys:
- primary: not necessary with increments
- unique
- index
- dropPrimary, dropUnique and dropIndex to drop indexes
- foreign key: $table->foreign("user_id")->references("id")->on("users)
- you can use onDelete(), onUpdate()
- dropForeign()
Running migrations:
- php artisan migrate: you can use --seed
- migrate:install: create table trackers (runs automatically with migrate)
- migrate:reset: rolls back all the migrations
- migrate:refresh: reset then migrate
- migrate:fresh: like refresh but doesn't run down(), it just deletes the tables
- migrate:rollback: rolls back the nth migration (--step=n)
- migrate:status: shows every migration and Y or N
Seeding:
- --seed to run the seeders with migration
- php artisan db:seed --class=VotesTableSeeder to run independently
- php artisan make:seeder ContactsTableSeeder: to create seeder
Factory models:
-
Query builder:
- DB::statement("drop table users"): I think it is like exec
- DB::select("select * from table where id = ?", [3])
- DB::table("users")->get()
Transactions:
- A group of commands to be done all, or no one if any one fails.
- DB::transaction(function() use ($userId, $numVotes){
DB::table() // etc
})
- for manual transactions
- DB::beginTransaction();
if($error) {
DB::rollback();
}
DB::commit();
== Eloquent ==
Making a model
- php artisan make:model (you can use --migration or -m to make a migration with it)
- for customizing default table props: $table, $primaryKey, $incrementing, $timestamp, $dateFormat(takes format like php date())
Getting data:
- first, find (OrFail)
- uset get() instead of all()
Chunk
- breaking the requests into smaller pieces
- Contact::chunk(100, function($contacts) {
foreach($contacts as $contact) {
}
})
- Aggregates: count, sum, avg
Insert and update with eloquent:
- Two primary ways:
= $contact = new Contact() or Contact:make, then $contact->save()
= Contact::create();
- Updating:
= $contact = Contact::find(). $contact->save();
= Contact::where("id", 20)->update(["name] => "Mohamed")
= $contact = Contact::find(), $contact->update(["name" => "Mohamed"]);
Mass assignment:
- protected $fillable, $guarded
- firstOrCreate(), firstOrNew()
Deleting:
- $contact = Contact::find(4)
$contact->delete();
- Contact::destroy(4);
- Contact::where()->delete();
Soft deletes:
- Enable it by doing three things:
= adding deleted_at column: $table->softDelete(), in the migration
= import the Trait, softDelete
= $dates = ["deleted_at"] in the Model
- Contact::withTrashed()->get()
- $contact->isTrashed() -> boolean
- Contact::onlyTrashed()->get()
- $contact->restore()
- $contact->forceDelete()
Scopes:
- Local scope: scopeScopeName($query, $property)
{
return $query->where("prop", $property);
}
- Global scopes:
- closure or class
- delete them with "withoutGlobalScope" or "withoutGlobalScopes(), accepts name or class, the second one accepts array of them and can exclude all when passed an empty array
Accessors:
- get custom attributes from models
- getTestAttribute => $model->test
Mutators:
- to change the value before inserting it to the database column
- getTestAttribute
Casts:
- to cast data from databse into some datatypes in laravel (Collection, Carbon...etc)
Collections:
- Tightanco/Collection package to use collections outside laravel
- create: collect([...array])
- reject? to delete some elements upon a condition
- map? to update all elements with a function
- sum()? reduce the collection into some number
- and more than 60 mehthods available on collection
- they are treated like normal arrays
- custom collections on models? newCollection($models)
Serialization:
- toArray()
- toJson()
- you can just use simple casting to string and the collection will use toJson()
- $appends, to add the extra columns to json output
- hidden, visible for displaying fields into the json response
- appends
-
Relationships:
- One to One:
- $this->hasOne(AnotherEloquent::class)
- $this->belongsTo()
- One to Many:
- $this->hasMany()
- $this->belongsTo()
- associate and dissociate
- Model::has('field') // returns only records that has related "field"
- whereHas
- hasManyThrough
- hasOneThrough
- Many to Many:
- pivot table: tabl1_table2 sorted alphapitically
- belongsToMany: in both models
- Child Updating timestamps
- touches
- Eager loading
- with()
- load()
- loadMissing()
- withCount()
Eloquent Events
-