Cover....1
Copyright....3
Table of Contents....6
Preface....20
What This Book Is About....20
Who This Book Is For....21
How This Book Is Structured....21
About the Third Edition....22
Conventions Used in This Book....22
O’Reilly Online Learning....23
How to Contact Us....23
Acknowledgements....24
Chapter 1. Why Laravel?....26
Why Use a Framework?....26
“I’ll Just Build It Myself”....27
Consistency and Flexibility....27
A Short History of Web and PHP Frameworks....27
Ruby on Rails....27
The Influx of PHP Frameworks....28
The Good and the Bad of CodeIgniter....28
Laravel 1, 2, and 3....28
Laravel 4....29
Laravel 5....29
Laravel 6....29
Laravel Versions in the New SemVer World (6+)....30
What’s So Special About Laravel?....30
The Philosophy of Laravel....30
How Laravel Achieves Developer Happiness....31
The Laravel Community....32
How It Works....32
Why Laravel?....35
Chapter 2. Setting Up a Laravel Development Environment....36
System Requirements....36
Composer....37
Local Development Environments....37
Artisan Serve....37
Laravel Sail....37
Laravel Valet....38
Laravel Herd....38
Laravel Homestead....38
Creating a New Laravel Project....39
Installing Laravel with the Laravel Installer Tool....39
Installing Laravel with Composer’s create-project Feature....39
Installing Laravel with Sail....39
Laravel’s Directory Structure....40
The Folders....40
The Loose Files....41
Configuration....42
The .env File....43
Up and Running....45
Testing....46
TL;DR....46
Chapter 3. Routing and Controllers....48
A Quick Introduction to MVC, the HTTP Verbs, and REST....48
What Is MVC?....48
The HTTP Verbs....49
What Is REST?....50
Route Definitions....51
Route Verbs....52
Route Handling....53
Route Parameters....54
Route Names....56
Route Groups....58
Middleware....59
Path Prefixes....60
Subdomain Routing....60
Name Prefixes....61
Route Group Controllers....62
Fallback Routes....62
Signed Routes....62
Signing a Route....63
Modifying Routes to Allow Signed Links....63
Views....64
Returning Simple Routes Directly with Route::view()....65
Using View Composers to Share Variables with Every View....65
Controllers....65
Getting User Input....68
Injecting Dependencies into Controllers....69
Resource Controllers....70
API Resource Controllers....72
Single Action Controllers....72
Route Model Binding....73
Implicit Route Model Binding....73
Custom Route Model Binding....75
Route Caching....75
Form Method Spoofing....76
HTTP Verbs in Laravel....76
HTTP Method Spoofing in HTML Forms....76
CSRF Protection....77
Redirects....78
redirect()->to()....79
redirect()->route()....79
redirect()->back()....80
Other Redirect Methods....80
redirect()->with()....81
Aborting the Request....83
Custom Responses....83
response()->make()....83
response()->json() and ->jsonp()....83
response()->download(), ->streamDownload(), and ->file()....84
Testing....84
TL;DR....85
Chapter 4. Blade Templating....86
Echoing Data....87
Control Structures....88
Conditionals....88
Loops....89
Template Inheritance....91
Defining Sections with @section/@show and @yield....91
Including View Partials....93
Using Components....95
Using Stacks....99
View Composers and Service Injection....100
Binding Data to Views Using View Composers....101
Blade Service Injection....104
Custom Blade Directives....105
Parameters in Custom Blade Directives....106
Example: Using Custom Blade Directives for a Multitenant App....106
Easier Custom Directives for “if” Statements....107
Testing....108
TL;DR....109
Chapter 5. Databases and Eloquent....110
Configuration....110
Database Connections....111
URL Configurations....112
Other Database Configuration Options....113
Migrations....113
Defining Migrations....113
Running Migrations....123
Inspecting Your Database....124
Seeding....124
Creating a Seeder....124
Model Factories....125
Query Builder....133
Basic Usage of the DB Facade....133
Raw SQL....134
Chaining with the Query Builder....135
Transactions....145
Introduction to Eloquent....146
Creating and Defining Eloquent Models....147
Retrieving Data with Eloquent....149
Inserts and Updates with Eloquent....151
Deleting with Eloquent....154
Scopes....157
Customizing Field Interactions with Accessors, Mutators, and Attribute Casting....160
Eloquent Collections....164
Eloquent Serialization....167
Eloquent Relationships....169
Eloquent Events....185
Testing....186
TL;DR....188
Chapter 6. Frontend Components....190
Laravel Starter Kits....190
Laravel Breeze....191
Laravel Jetstream....192
Laravel’s Vite Configuration....194
Bundling Files with Vite....196
The Vite Dev Server....196
Working with Static Assets and Vite....197
Working with JavaScript Frameworks and Vite....198
Using Environment Variables in Vite....199
Pagination....200
Paginating Database Results....200
Manually Creating Paginators....202
Message Bags....203
String Helpers, Pluralization, and Localization....204
The String Helpers and Pluralization....205
Localization....206
Testing....210
Testing Message and Error Bags....210
Translation and Localization....210
Disabling Vite in Testing....210
TL;DR....211
Chapter 7. Collecting and Handling User Data....212
Injecting a Request Object....212
$request->all()....213
$request->except() and ->only()....213
$request->has() and ->missing()....214
$request->whenHas()....214
$request->filled()....215
$request->whenFilled()....215
$request->mergeIfMissing()....215
$request->input()....216
$request->method() and ->isMethod()....216
$request->integer(), ->float(), ->string(), and ->enum()....216
$request->dump() and ->dd()....217
Array Input....217
JSON Input (and $request->json())....218
Route Data....219
From Request....219
From Route Parameters....220
Uploaded Files....220
Validation....222
validate() on the Request Object....223
More on Laravel’s Validation Rules....224
Manual Validation....225
Using Validated Data....225
Custom Rule Objects....226
Displaying Validation Error Messages....227
Form Requests....227
Creating a Form Request....228
Using a Form Request....229
Eloquent Model Mass Assignment....229
{{ Versus {!!....231
Testing....231
TL;DR....232
Chapter 8. Artisan and Tinker....234
An Introduction to Artisan....234
Basic Artisan Commands....235
Options....236
The Grouped Commands....237
Writing Custom Artisan Commands....239
A Sample Command....240
Arguments and Options....241
Using Input....243
Prompts....245
Output....246
Writing Closure-Based Commands....247
Calling Artisan Commands in Normal Code....248
Tinker....249
Laravel Dump Server....250
Customizing Generator Stubs....251
Testing....251
TL;DR....252
Chapter 9. User Authentication and Authorization....254
The User Model and Migration....254
Using the auth() Global Helper and the Auth Facade....258
routes/auth.php, Auth Controllers, and Auth Actions....258
Breeze and Jetstream’s Frontend Templates....260
“Remember Me”....260
Password Confirmation....261
Manually Authenticating Users....261
Manually Logging Out a User....262
Invalidating Sessions on Other Devices....262
Auth Middleware....262
Email Verification....264
Blade Authentication Directives....264
Guards....265
Changing the Default Guard....265
Using Other Guards Without Changing the Default....266
Adding a New Guard....266
Closure Request Guards....266
Creating a Custom User Provider....267
Custom User Providers for Nonrelational Databases....268
Auth Events....268
Authorization and Roles....269
Defining Authorization Rules....269
The Gate Facade (and Injecting Gate)....270
Resource Gates....271
The Authorize Middleware....271
Controller Authorization....272
Checking the User Instance....274
Blade Checks....274
Intercepting Checks....275
Policies....275
Testing....278
TL;DR....280
Chapter 10. Requests, Responses, and Middleware....282
Laravel’s Request Lifecycle....282
Bootstrapping the Application....283
Service Providers....284
The Request Object....285
Getting a Request Object in Laravel....286
Getting Basic Information About a Request....287
The Response Object....291
Using and Creating Response Objects in Controllers....291
Specialized Response Types....292
Laravel and Middleware....298
An Introduction to Middleware....298
Creating Custom Middleware....299
Binding Middleware....301
Passing Parameters to Middleware....304
Default Middleware....305
Maintenance Mode....305
Rate Limiting....305
Trusted Proxies....306
CORS....307
Testing....307
TL;DR....308
Chapter 11. The Container....310
A Quick Introduction to Dependency Injection....310
Dependency Injection and Laravel....312
The app() Global Helper....312
How the Container Is Wired....313
Binding Classes to the Container....314
Binding to a Closure....314
Binding to Singletons, Aliases, and Instances....315
Binding a Concrete Instance to an Interface....316
Contextual Binding....317
Constructor Injection in Laravel Framework Files....318
Method Injection....318
Facades and the Container....320
How Facades Work....320
Real-Time Facades....322
Service Providers....322
Testing....323
TL;DR....324
Chapter 12. Testing....326
Testing Basics....327
Naming Tests....330
The Testing Environment....331
The Testing Traits....332
RefreshDatabase....332
DatabaseMigrations....332
DatabaseTransactions....333
WithoutMiddleware....333
Simple Unit Tests....333
Application Testing: How It Works....334
HTTP Tests....335
Testing Basic Pages with $this->get() and Other HTTP Calls....335
Testing JSON APIs with $this->getJson() and Other JSON HTTP Calls....336
Assertions Against $response....337
Authenticating Responses....340
A Few Other Customizations to Your HTTP Tests....341
Handling Exceptions in Application Tests....341
Debugging Responses....342
Database Tests....342
Asserting Against the Database....343
Asserting Against Eloquent Models....343
Using Model Factories in Tests....344
Seeding in Tests....344
Testing Other Laravel Systems....344
Event Fakes....344
Bus and Queue Fakes....346
Mail Fakes....347
Notification Fakes....348
Storage Fakes....349
Working with Time in Tests....350
Mocking....351
A Quick Introduction to Mocking....351
A Quick Introduction to Mockery....351
Faking Other Facades....354
Testing Artisan Commands....355
Parallel Testing....357
Browser Tests....357
Choosing a Tool....357
Testing with Dusk....357
Pest....369
TL;DR....369
Chapter 13. Writing APIs....370
The Basics of REST-Like JSON APIs....370
Controller Organization and JSON Returns....372
Reading and Sending Headers....375
Sending Response Headers in Laravel....376
Reading Request Headers in Laravel....376
Eloquent Pagination....376
Sorting and Filtering....378
Sorting Your API Results....379
Filtering Your API Results....380
Transforming Results....381
API Resources....382
Creating a Resource Class....382
Resource Collections....383
Nesting Relationships....385
Using Pagination with API Resources....386
Conditionally Applying Attributes....387
More Customizations for API Resources....388
API Authentication....388
API Authentication with Sanctum....388
API Authentication with Laravel Passport....392
Customizing 404 Responses....404
Triggering the Fallback Route....404
Testing....405
Testing Passport....405
TL;DR....406
Chapter 14. Storage and Retrieval....408
Local and Cloud File Managers....408
Configuring File Access....408
Using the Storage Facade....410
Adding Additional Flysystem Providers....412
Basic File Uploads and Manipulation....412
Simple File Downloads....414
Sessions....414
Accessing the Session....414
Methods Available on Session Instances....415
Flash Session Storage....417
Cache....417
Accessing the Cache....418
Methods Available on Cache Instances....418
Cookies....420
Cookies in Laravel....420
Accessing the Cookie Tools....420
Logging....423
When and Why to Use Logs....424
Writing to the Logs....424
Log Channels....425
Full-Text Search with Laravel Scout....427
Installing Scout....428
Marking Your Model for Indexing....428
Searching Your Index....428
Queues and Scout....429
Performing Operations Without Indexing....429
Conditionally Indexing Models....429
Manually Triggering Indexing via Code....429
Manually Triggering Indexing via the CLI....430
The HTTP Client....430
Using the HTTP Facade....430
Handling Errors and Timeouts and Checking Statuses....431
Testing....432
File Storage....432
Session....434
Cache....435
Cookies....435
Log....436
Scout....437
HTTP Client....437
TL;DR....438
Chapter 15. Mail and Notifications....440
Mail....440
Basic “Mailable” Mail Usage....441
Mail Templates....444
Methods Available in envelope()....445
Attaching Files and Inlining Images....446
Markdown Mailables....448
Rendering Mailables to the Browser....450
Queues....451
Local Development....451
Notifications....453
Defining the via() Method for Your Notifiables....455
Sending Notifications....456
Queueing Notifications....457
Out-of-the-Box Notification Types....457
Testing....461
Mail....461
Notifications....463
TL;DR....464
Chapter 16. Queues, Jobs, Events, Broadcasting, and the Scheduler....466
Queues....466
Why Queues?....467
Basic Queue Configuration....467
Queued Jobs....468
Running a Queue Worker....474
Handling Errors....474
Controlling the Queue....479
Queues Supporting Other Functions....479
Laravel Horizon....479
Events....480
Firing an Event....481
Listening for an Event....482
Broadcasting Events Over WebSockets, and Laravel Echo....486
Configuration and Setup....487
Broadcasting an Event....487
Receiving the Message....490
Advanced Broadcasting Tools....492
Laravel Echo (the JavaScript Side)....496
Scheduler....500
Available Task Types....501
Available Time Frames....501
Defining Time Zones for Scheduled Commands....503
Blocking and Overlap....504
Handling Task Output....504
Task Hooks....505
Running the Scheduler in Local Development....505
Testing....505
TL;DR....507
Chapter 17. Helpers and Collections....508
Helpers....508
Arrays....508
Strings....511
Application Paths....514
URLs....515
Miscellaneous....517
Collections....520
The Basics....520
A Few Collection Operations....522
TL;DR....528
Chapter 18. The Laravel Ecosystem....530
Tools Covered in This Book....530
Valet....530
Homestead....530
Herd....531
The Laravel Installer....531
Dusk....531
Passport....531
Sail....531
Sanctum....531
Fortify....532
Breeze....532
Jetstream....532
Horizon....532
Echo....532
Tools Not Covered in This Book....532
Forge....533
Vapor....533
Envoyer....533
Cashier....534
Socialite....534
Nova....534
Spark....535
Envoy....535
Telescope....535
Octane....535
Pennant....536
Folio....536
Volt....536
Pint....536
Other Resources....536
Glossary....538
Index....546
About the Author....560
Colophon....560
What sets Laravel apart from other PHP web frameworks? Speed and simplicity, for starters. This rapid application development framework and its ecosystem of tools let you quickly build new sites and applications with clean, readable code. Fully updated to cover Laravel 5.8, the second edition of this practical guide provides the definitive introduction to one of today’s mostpopular web frameworks.
Matt Stauffer, a leading teacher and developer in the Laravel community, delivers a high-level overview and concrete examples to help experienced PHP web developers get started with this framework right away. This updated edition also covers Laravel Dusk and Horizon and provides information about community resources and other noncore Laravel packages.