100% found this document useful (1 vote)
11 views

Building Real-Time Marvels with Laravel: Create Dynamic and Interactive Web Applications 1st Edition Sivaraj Selvaraj pdf download

The document provides information on various ebooks available for download at ebookmass.com, including titles on Laravel, SwiftUI, Angular, and more. It features a detailed overview of the book 'Building Real-Time Marvels with Laravel' by Sivaraj Selvaraj, outlining its content and structure. Additionally, it includes links to other recommended ebooks and information about the authors and publishers.

Uploaded by

melynguyo
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
11 views

Building Real-Time Marvels with Laravel: Create Dynamic and Interactive Web Applications 1st Edition Sivaraj Selvaraj pdf download

The document provides information on various ebooks available for download at ebookmass.com, including titles on Laravel, SwiftUI, Angular, and more. It features a detailed overview of the book 'Building Real-Time Marvels with Laravel' by Sivaraj Selvaraj, outlining its content and structure. Additionally, it includes links to other recommended ebooks and information about the authors and publishers.

Uploaded by

melynguyo
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 76

Download the full version and explore a variety of ebooks

or textbooks at https://ebookmass.com

Building Real-Time Marvels with Laravel: Create


Dynamic and Interactive Web Applications 1st
Edition Sivaraj Selvaraj

_____ Follow the link below to get your download now _____

https://ebookmass.com/product/building-real-time-marvels-
with-laravel-create-dynamic-and-interactive-web-
applications-1st-edition-sivaraj-selvaraj/

Access ebookmass.com now to download high-quality


ebooks or textbooks
We have selected some products that you may be interested in
Click the link to download now or visit ebookmass.com
for more options!.

Building Real-Time Marvels with Laravel: Create Dynamic


and Interactive Web Applications 1st Edition Sivaraj
Selvaraj
https://ebookmass.com/product/building-real-time-marvels-with-laravel-
create-dynamic-and-interactive-web-applications-1st-edition-sivaraj-
selvaraj/

Build Mobile Apps with SwiftUI and Firebase: Learn SwiftUI


and Firebase by Building Real-World Applications
Communicating with a Backend 1st Edition Sullivan De Carli
https://ebookmass.com/product/build-mobile-apps-with-swiftui-and-
firebase-learn-swiftui-and-firebase-by-building-real-world-
applications-communicating-with-a-backend-1st-edition-sullivan-de-
carli/

Biological Reaction Engineering: Dynamic Modeling


Fundamentals with 80 Interactive Simulation Examples 3rd
Edition Elmar Heinzle
https://ebookmass.com/product/biological-reaction-engineering-dynamic-
modeling-fundamentals-with-80-interactive-simulation-examples-3rd-
edition-elmar-heinzle/

Getting Started with Angular: Create and Deploy Angular


Applications 1st Edition Victor Hugo Garcia

https://ebookmass.com/product/getting-started-with-angular-create-and-
deploy-angular-applications-1st-edition-victor-hugo-garcia/
How To Create Wealth Investing In Real Estate: How to
Build Wealth with Multi-Family Real Estate

https://ebookmass.com/product/how-to-create-wealth-investing-in-real-
estate-how-to-build-wealth-with-multi-family-real-estate/

Serverless Web Applications with AWS Amplify: Build Full-


Stack Serverless Applications Using Amazon Web Services
Akshat Paul
https://ebookmass.com/product/serverless-web-applications-with-aws-
amplify-build-full-stack-serverless-applications-using-amazon-web-
services-akshat-paul/

Developing Web Components with Svelte: Building a Library


of Reusable UI Components 1st Edition Alex Libby

https://ebookmass.com/product/developing-web-components-with-svelte-
building-a-library-of-reusable-ui-components-1st-edition-alex-libby/

Optimizations and Programming: Linear, Non-linear,


Dynamic, Stochastic and Applications with Matlab
Abdelkhalak El Hami
https://ebookmass.com/product/optimizations-and-programming-linear-
non-linear-dynamic-stochastic-and-applications-with-matlab-
abdelkhalak-el-hami/

Beginner's Guide to Streamlit with Python: Build Web-Based


Data and Machine Learning Applications 1st Edition Sujay
Raghavendra
https://ebookmass.com/product/beginners-guide-to-streamlit-with-
python-build-web-based-data-and-machine-learning-applications-1st-
edition-sujay-raghavendra/
Building Real-Time
Marvels with Laravel
Create Dynamic and Interactive Web
Applications

Sivaraj Selvaraj
Building Real-Time Marvels with Laravel: Create Dynamic and Interactive Web
Applications
Sivaraj Selvaraj
Ulundurpettai, Tamil Nadu, India

ISBN-13 (pbk): 978-1-4842-9788-9 ISBN-13 (electronic): 978-1-4842-9789-6


https://doi.org/10.1007/978-1-4842-9789-6

Copyright © 2024 by Sivaraj Selvaraj


This work is subject to copyright. All rights are reserved by the Publisher, whether the whole or part of the
material is concerned, specifically the rights of translation, reprinting, reuse of illustrations, recitation,
broadcasting, reproduction on microfilms or in any other physical way, transmission or information storage
and retrieval, electronic adaptation, computer software, or by similar or dissimilar methodologies now
known or hereafter developed.
Trademarked names, logos, and images may appear in this book. Rather than using a trademark symbol
with every occurrence of a trademarked name, logo, or image, we use the names, logos, and images only in
an editorial fashion and to the benefit of the trademark owner, with no intention of infringement of the
trademark.
The use in this publication of trade names, trademarks, service marks, and similar terms, even if they are not
identified as such, is not to be taken as an expression of opinion as to whether or not they are subject to
proprietary rights.
While the advice and information in this book are believed to be true and accurate at the date of publication,
neither the authors, the editors, nor the publisher can accept any legal responsibility for any errors or
omissions that may be made. The publisher makes no warranty, express or implied, with respect to the
material contained herein.
Managing Director, Apress Media LLC: Welmoed Spahr
Acquisitions Editor: Divya Modi
Development Editor: James Markham
Editorial Assistant: Divya Modi
Cover image designed by Freepik (www.freepik.com)
Distributed to the book trade worldwide by Springer Science+Business Media New York, 1 New York Plaza,
Suite 4600, New York, NY 10004-1562, USA. Phone 1-800-SPRINGER, fax (201) 348-4505, e-mail orders-ny@
springer-sbm.com, or visit www.springeronline.com. Apress Media, LLC is a California LLC and the sole
member (owner) is Springer Science + Business Media Finance Inc (SSBM Finance Inc). SSBM Finance Inc
is a Delaware corporation.
For information on translations, please e-mail [email protected]; for reprint,
paperback, or audio rights, please e-mail [email protected].
Apress titles may be purchased in bulk for academic, corporate, or promotional use. eBook versions and
licenses are also available for most titles. For more information, reference our Print and eBook Bulk Sales
web page at http://www.apress.com/bulk-sales.
Any source code or other supplementary material referenced by the author in this book is available to
readers on GitHub (github.com/apress). For more detailed information, please visit https://www.apress.
com/gp/services/source-code.
Paper in this product is recyclable
This book is dedicated with profound love and gratitude to my beloved
family and dearest friends, who have stood as unwavering pillars of
support throughout my remarkable journey.
To my ever-supportive parents, whose boundless encouragement and
unwavering belief in my abilities have been the guiding light that led
me to this point.
To my dear sister and Sri Jaya Surya V, whose companionship and
camaraderie have filled every step of this journey with joy and
meaning.
Thank you all from the depths of my heart for being an integral part of
this incredible journey. This book is a testament to your unwavering
belief in me and a humble token of my deep appreciation for the
boundless love and support you have showered upon me.
With heartfelt appreciation and love.
Table of Contents
About the Author�������������������������������������������������������������������������������������������������xxvii

About the Technical Reviewer������������������������������������������������������������������������������xxix


Acknowledgments������������������������������������������������������������������������������������������������xxxi

Introduction��������������������������������������������������������������������������������������������������������xxxiii

Chapter 1: Understanding the Laravel Ecosystem���������������������������������������������������� 1


Introduction to the Laravel Ecosystem������������������������������������������������������������������������������������������ 2
MVC Pattern����������������������������������������������������������������������������������������������������������������������������� 3
Setting Up the Development Environment������������������������������������������������������������������������������������ 5
PHP (Hypertext Preprocessor)������������������������������������������������������������������������������������������������� 5
Web Server������������������������������������������������������������������������������������������������������������������������������ 5
Database (DB)�������������������������������������������������������������������������������������������������������������������������� 6
Composer�������������������������������������������������������������������������������������������������������������������������������� 6
Key Concepts and Principles of Laravel���������������������������������������������������������������������������������������� 9
Routing������������������������������������������������������������������������������������������������������������������������������������ 9
Controllers����������������������������������������������������������������������������������������������������������������������������� 10
Views������������������������������������������������������������������������������������������������������������������������������������� 13
Models����������������������������������������������������������������������������������������������������������������������������������� 14
Migrations����������������������������������������������������������������������������������������������������������������������������� 15
Middleware���������������������������������������������������������������������������������������������������������������������������� 16
Exploring the Laravel Ecosystem������������������������������������������������������������������������������������������������ 17
Laravel Packages������������������������������������������������������������������������������������������������������������������ 17
Summary������������������������������������������������������������������������������������������������������������������������������������ 19

v
Table of Contents

Chapter 2: Advanced Routing Techniques�������������������������������������������������������������� 21


Route Parameters and Wildcards������������������������������������������������������������������������������������������������ 22
Route Parameters������������������������������������������������������������������������������������������������������������������ 22
Wildcards������������������������������������������������������������������������������������������������������������������������������� 23
Route Model Binding������������������������������������������������������������������������������������������������������������������� 25
Route Binding������������������������������������������������������������������������������������������������������������������������ 25
Customizing Route Model Binding����������������������������������������������������������������������������������������� 27
Benefits of Route Model Binding������������������������������������������������������������������������������������������� 30
Route Caching����������������������������������������������������������������������������������������������������������������������������� 31
Ideal Cases for Enabling Route Caching�������������������������������������������������������������������������������� 32
Ideal Scenarios to Disable Route Caching����������������������������������������������������������������������������� 32
Enabling and Disabling Route Caching���������������������������������������������������������������������������������� 33
Benefits of Route Caching����������������������������������������������������������������������������������������������������� 33
Considerations and Limitations��������������������������������������������������������������������������������������������� 35
Middleware and Route Grouping������������������������������������������������������������������������������������������������� 36
Middleware���������������������������������������������������������������������������������������������������������������������������� 36
Route Grouping���������������������������������������������������������������������������������������������������������������������� 38
Benefits of Middleware and Route Grouping������������������������������������������������������������������������� 40
Route Model Binding for Polymorphic Relations������������������������������������������������������������������� 40
Route Model Binding with Polymorphic Relations����������������������������������������������������������������� 42
Customizing Polymorphic Route Model Binding�������������������������������������������������������������������� 43
Benefits of Route Model Binding for Polymorphic Relations������������������������������������������������� 44
Summary������������������������������������������������������������������������������������������������������������������������������������ 45

Chapter 3: Database Management and Eloquent ORM������������������������������������������� 47


Working with Database Migrations��������������������������������������������������������������������������������������������� 48
Database Migrations Provide Several Benefits��������������������������������������������������������������������� 48
Creating Migrations��������������������������������������������������������������������������������������������������������������� 49
Running Migrations��������������������������������������������������������������������������������������������������������������� 50
Modifying Migrations������������������������������������������������������������������������������������������������������������� 51
Migration Rollback and Refresh�������������������������������������������������������������������������������������������� 52

vi
Table of Contents

To Avoid Unwanted Consequences���������������������������������������������������������������������������������������� 53


Benefits of Database Migrations������������������������������������������������������������������������������������������� 54
Querying the Database with Eloquent����������������������������������������������������������������������������������������� 55
Retrieving Models������������������������������������������������������������������������������������������������������������������ 55
Query Constraints������������������������������������������������������������������������������������������������������������������ 56
Relationships������������������������������������������������������������������������������������������������������������������������� 56
Creating and Updating Models���������������������������������������������������������������������������������������������� 57
Deleting Models��������������������������������������������������������������������������������������������������������������������� 58
Lazy Loading and Eager Loading������������������������������������������������������������������������������������������� 58
Advantages of Eager Loading������������������������������������������������������������������������������������������������ 59
Cons of Eager Loading����������������������������������������������������������������������������������������������������������� 59
Advantages of Lazy Loading�������������������������������������������������������������������������������������������������� 60
Cons of Lazy Loading������������������������������������������������������������������������������������������������������������� 60
Choosing the Right Approach������������������������������������������������������������������������������������������������ 60
Eloquent Relationships: One-to-One, One-to-Many, and Many-to-Many������������������������������������ 61
One-to-One Relationship������������������������������������������������������������������������������������������������������� 62
One-to-Many Relationship����������������������������������������������������������������������������������������������������� 63
Many-to-Many Relationship�������������������������������������������������������������������������������������������������� 65
Advanced Eloquent Techniques: Polymorphic Relations and Query Scopes������������������������������� 67
Polymorphic Relations����������������������������������������������������������������������������������������������������������� 67
Query Scopes������������������������������������������������������������������������������������������������������������������������ 69
Advanced Eloquent Techniques Summary����������������������������������������������������������������������������� 70
Using Eloquent Collections and Serialization������������������������������������������������������������������������������ 70
Eloquent Collections�������������������������������������������������������������������������������������������������������������� 70
Serialization��������������������������������������������������������������������������������������������������������������������������� 71
Using Eloquent Collections and Serialization Summary�������������������������������������������������������� 72
Summary������������������������������������������������������������������������������������������������������������������������������������ 73

vii
Table of Contents

Chapter 4: Authentication and Authorization��������������������������������������������������������� 75


User Authentication: Registration, Login, and Logout����������������������������������������������������������������� 76
User Registration������������������������������������������������������������������������������������������������������������������� 76
User Login����������������������������������������������������������������������������������������������������������������������������� 80
User Logout��������������������������������������������������������������������������������������������������������������������������� 82
Authentication Guards and Providers������������������������������������������������������������������������������������������ 84
Authentication Guards����������������������������������������������������������������������������������������������������������� 85
Authentication Providers������������������������������������������������������������������������������������������������������� 86
Customizing Authentication Guards and Providers���������������������������������������������������������������� 88
Authentication Guards and Providers Summary�������������������������������������������������������������������� 89
Managing User Roles and Permissions��������������������������������������������������������������������������������������� 90
User Roles����������������������������������������������������������������������������������������������������������������������������� 90
User Permissions������������������������������������������������������������������������������������������������������������������� 92
Implementing Role-Based Access Control (RBAC)����������������������������������������������������������������� 94
Managing User Roles and Permissions Summary����������������������������������������������������������������� 96
Advanced Authorization Techniques: Gates and Policies������������������������������������������������������������ 97
Gates������������������������������������������������������������������������������������������������������������������������������������� 97
Policies���������������������������������������������������������������������������������������������������������������������������������� 98
Resource Controllers and Implicit Model Binding��������������������������������������������������������������� 100
Advanced Authorization Techniques Summary�������������������������������������������������������������������� 101
Summary���������������������������������������������������������������������������������������������������������������������������������� 101

Chapter 5: Building APIs with Laravel������������������������������������������������������������������ 103


Introduction to API Development����������������������������������������������������������������������������������������������� 104
Building RESTful APIs with Laravel������������������������������������������������������������������������������������������� 105
Resourceful Routing������������������������������������������������������������������������������������������������������������ 105
Folder Structure (API-Specific)�������������������������������������������������������������������������������������������� 109
API Authentication and Security������������������������������������������������������������������������������������������������ 110
Token-Based Authentication������������������������������������������������������������������������������������������������ 110
JWT Authentication�������������������������������������������������������������������������������������������������������������� 111
Best Practices for Using JWT in Laravel������������������������������������������������������������������������������ 111

viii
Table of Contents

API Throttling����������������������������������������������������������������������������������������������������������������������� 114


CORS (Cross-Origin Resource Sharing)������������������������������������������������������������������������������� 114
API Rate Limiting and Throttling����������������������������������������������������������������������������������������������� 115
Rate Limiting����������������������������������������������������������������������������������������������������������������������� 116
Throttling����������������������������������������������������������������������������������������������������������������������������� 116
Customizing Rate Limiting and Throttling��������������������������������������������������������������������������� 117
Handling Rate Limit Exceeded Responses�������������������������������������������������������������������������� 117
Handling API Errors and Exceptions������������������������������������������������������������������������������������������ 118
Exception Handling�������������������������������������������������������������������������������������������������������������� 118
Error Formatting������������������������������������������������������������������������������������������������������������������ 119
Error Responses������������������������������������������������������������������������������������������������������������������ 120
Logging and Debugging������������������������������������������������������������������������������������������������������� 120
Error Handling for Validation Errors������������������������������������������������������������������������������������� 121
Summary���������������������������������������������������������������������������������������������������������������������������������� 122

Chapter 6: Caching and Performance Optimization���������������������������������������������� 123


Understanding Laravel’s Cache System������������������������������������������������������������������������������������ 124
Cache Drivers���������������������������������������������������������������������������������������������������������������������� 124
Cache Tags�������������������������������������������������������������������������������������������������������������������������� 125
Cache Invalidation��������������������������������������������������������������������������������������������������������������� 126
Implementing Caching with Redis and Memcached����������������������������������������������������������������� 127
Configuring Redis as the Cache Driver�������������������������������������������������������������������������������� 128
Configuring Memcached as the Cache Driver��������������������������������������������������������������������� 128
Using Redis or Memcached for Caching������������������������������������������������������������������������������ 129
Cache Tagging and Cache Invalidation�������������������������������������������������������������������������������������� 131
Cache Tagging��������������������������������������������������������������������������������������������������������������������� 131
Retrieving Data by Tag��������������������������������������������������������������������������������������������������������� 133
Flushing Cache by Tag��������������������������������������������������������������������������������������������������������� 134
Optimizing Database Queries with Eager Loading�������������������������������������������������������������������� 135
Understanding Eager Loading��������������������������������������������������������������������������������������������� 136

ix
Table of Contents

Performance Optimization Techniques for Laravel Applications����������������������������������������������� 140


Code Optimization��������������������������������������������������������������������������������������������������������������� 140
Caching�������������������������������������������������������������������������������������������������������������������������������� 140
Database Optimization�������������������������������������������������������������������������������������������������������� 140
Lazy Loading vs. Eager Loading������������������������������������������������������������������������������������������ 141
Code Profiling and Monitoring��������������������������������������������������������������������������������������������� 141
Asset Optimization��������������������������������������������������������������������������������������������������������������� 141
HTTP Caching���������������������������������������������������������������������������������������������������������������������� 142
Optimized Configurations���������������������������������������������������������������������������������������������������� 142
Queue Optimization������������������������������������������������������������������������������������������������������������� 143
Server Optimization������������������������������������������������������������������������������������������������������������� 143
Summary���������������������������������������������������������������������������������������������������������������������������������� 144

Chapter 7: Advanced Middleware Techniques������������������������������������������������������ 145


Creating Custom Middleware���������������������������������������������������������������������������������������������������� 146
Creating Custom Middleware���������������������������������������������������������������������������������������������� 147
Middleware Pipeline and Terminable Middleware�������������������������������������������������������������������� 152
Middleware Pipeline������������������������������������������������������������������������������������������������������������ 153
Terminable Middleware������������������������������������������������������������������������������������������������������� 154
Illustration: Terminable Middleware������������������������������������������������������������������������������������ 155
Middleware Parameters and Dependencies����������������������������������������������������������������������������� 156
Middleware Parameters������������������������������������������������������������������������������������������������������ 156
Middleware Dependencies�������������������������������������������������������������������������������������������������� 158
Global Middleware vs. Route Middleware��������������������������������������������������������������������������������� 160
Global Middleware��������������������������������������������������������������������������������������������������������������� 161
Route Middleware��������������������������������������������������������������������������������������������������������������� 162
Middleware Best Practices and Performance Considerations�������������������������������������������������� 164
Keep Middleware Focused�������������������������������������������������������������������������������������������������� 164
Order of Middleware Matters���������������������������������������������������������������������������������������������� 165
Use Middleware Groups������������������������������������������������������������������������������������������������������ 165
Apply Middleware Selectively���������������������������������������������������������������������������������������������� 165
Middleware Parameters and Dependencies������������������������������������������������������������������������ 165

x
Table of Contents

Performance Considerations����������������������������������������������������������������������������������������������� 165


Error Handling and Exceptions�������������������������������������������������������������������������������������������� 166
Testing Middleware������������������������������������������������������������������������������������������������������������� 166
Summary���������������������������������������������������������������������������������������������������������������������������������� 166

Chapter 8: Real-Time Applications with Laravel�������������������������������������������������� 167


Real-Time Applications: An Overview��������������������������������������������������������������������������������������� 168
Building Real-Time Features with Laravel WebSockets������������������������������������������������������������ 169
Installation and Configuration��������������������������������������������������������������������������������������������� 169
Broadcasting Events with Laravel Echo������������������������������������������������������������������������������������ 171
Setting Up Laravel Echo������������������������������������������������������������������������������������������������������ 171
Configure Laravel Echo�������������������������������������������������������������������������������������������������������� 172
Listening for Events with Laravel Echo������������������������������������������������������������������������������� 175
Joining Channels����������������������������������������������������������������������������������������������������������������� 178
Handling Events������������������������������������������������������������������������������������������������������������������� 180
Presence Channels�������������������������������������������������������������������������������������������������������������� 180
Private Channels������������������������������������������������������������������������������������������������������������������ 183
Additional Features������������������������������������������������������������������������������������������������������������� 185
Creating Real-Time Notifications and Chat Applications����������������������������������������������������������� 188
Real-Time Notifications������������������������������������������������������������������������������������������������������� 188
Chat Applications����������������������������������������������������������������������������������������������������������������� 191
Real-Time Presence������������������������������������������������������������������������������������������������������������ 192
Private Messaging��������������������������������������������������������������������������������������������������������������� 195
Summary���������������������������������������������������������������������������������������������������������������������������������� 197

Chapter 9: Testing and Test-Driven Development������������������������������������������������� 199


Introduction to Testing in Laravel���������������������������������������������������������������������������������������������� 200
Writing Unit Tests with PHPUnit������������������������������������������������������������������������������������������������ 201
Generating a Test Class������������������������������������������������������������������������������������������������������� 201
Writing Test Methods����������������������������������������������������������������������������������������������������������� 201
Running Unit Tests��������������������������������������������������������������������������������������������������������������� 203
Mocking Dependencies������������������������������������������������������������������������������������������������������� 203
Best Practices for Unit Testing��������������������������������������������������������������������������������������������� 205
xi
Table of Contents

Testing HTTP Requests and Responses������������������������������������������������������������������������������������ 205


Writing Feature Tests����������������������������������������������������������������������������������������������������������� 206
Test-Driven Development (TDD) Workflow�������������������������������������������������������������������������������� 209
Write a Test�������������������������������������������������������������������������������������������������������������������������� 210
Run the Test������������������������������������������������������������������������������������������������������������������������� 210
Write the Code��������������������������������������������������������������������������������������������������������������������� 211
Run the Test Again��������������������������������������������������������������������������������������������������������������� 212
Refactor the Code (Optional)����������������������������������������������������������������������������������������������� 212
Advantages of Test-Driven Development (TDD)������������������������������������������������������������������� 213
Testing API Endpoints and Integrations������������������������������������������������������������������������������������� 214
Writing Feature Tests for API Endpoints������������������������������������������������������������������������������ 214
Summary���������������������������������������������������������������������������������������������������������������������������������� 218

Chapter 10: Queues and Job Scheduling�������������������������������������������������������������� 219


Introduction to Queues and Workers����������������������������������������������������������������������������������������� 220
Here’s How the Process Works�������������������������������������������������������������������������������������������� 220
Benefits of Using Queues and Workers������������������������������������������������������������������������������� 220
Laravel’s Integration of Queues and Workers���������������������������������������������������������������������� 221
Setting Up Queue Drivers and Connections������������������������������������������������������������������������������ 221
Choose a Queue Driver�������������������������������������������������������������������������������������������������������� 221
Configure the Queue Connection����������������������������������������������������������������������������������������� 222
Creating and Dispatching Jobs������������������������������������������������������������������������������������������������� 224
Create the Job Class������������������������������������������������������������������������������������������������������������ 225
Define the Job Logic������������������������������������������������������������������������������������������������������������ 225
Dispatch the Job������������������������������������������������������������������������������������������������������������������ 226
Illustration: Image Processing��������������������������������������������������������������������������������������������� 227
Managing Failed Jobs and Retries�������������������������������������������������������������������������������������������� 229
Understanding Failed Jobs�������������������������������������������������������������������������������������������������� 230
Scheduling Jobs with Laravel’s Task Scheduler����������������������������������������������������������������������� 233
Define the Scheduled Jobs in Kernel.php��������������������������������������������������������������������������� 233
Scheduling Artisan Commands�������������������������������������������������������������������������������������������� 233

xii
Table of Contents

Using Cron Expressions������������������������������������������������������������������������������������������������������� 234


Register the Scheduler in Cron�������������������������������������������������������������������������������������������� 235
Summary���������������������������������������������������������������������������������������������������������������������������������� 235

Chapter 11: Advanced Package Development������������������������������������������������������ 237


Introduction to Package Development in Laravel��������������������������������������������������������������������� 238
Setting Up the Package Structure��������������������������������������������������������������������������������������� 238
Creating Custom Service Providers������������������������������������������������������������������������������������������ 240
Create the Service Provider Class��������������������������������������������������������������������������������������� 240
Register Bindings and Services������������������������������������������������������������������������������������������� 240
Load the Service Provider��������������������������������������������������������������������������������������������������� 241
Additional Configuration (if Required)��������������������������������������������������������������������������������� 241
Using the Package’s Functionality��������������������������������������������������������������������������������������� 241
Publishing Configuration and Assets���������������������������������������������������������������������������������������� 241
Publishing Configuration����������������������������������������������������������������������������������������������������� 242
Publishing Assets���������������������������������������������������������������������������������������������������������������� 243
Registering the Assets��������������������������������������������������������������������������������������������������������� 244
Testing and Versioning Packages���������������������������������������������������������������������������������������������� 245
Testing Packages����������������������������������������������������������������������������������������������������������������� 245
Continuous Integration (CI)�������������������������������������������������������������������������������������������������� 249
Communication and Backward Compatibility���������������������������������������������������������������������� 253
Packaging and Distributing Laravel Packages�������������������������������������������������������������������������� 253
Package Structure��������������������������������������������������������������������������������������������������������������� 253
Create a Composer Package����������������������������������������������������������������������������������������������� 254
Publish Your Package���������������������������������������������������������������������������������������������������������� 255
Register Your Package��������������������������������������������������������������������������������������������������������� 255
Versioning and Tagging������������������������������������������������������������������������������������������������������� 255
Installation via Composer���������������������������������������������������������������������������������������������������� 256
Documentation�������������������������������������������������������������������������������������������������������������������� 256
Summary���������������������������������������������������������������������������������������������������������������������������������� 257

xiii
Table of Contents

Chapter 12: Performance Monitoring and Debugging������������������������������������������ 259


Profiling Laravel Applications���������������������������������������������������������������������������������������������������� 260
Laravel Debugbar���������������������������������������������������������������������������������������������������������������� 261
Xdebug�������������������������������������������������������������������������������������������������������������������������������� 263
Blackfire������������������������������������������������������������������������������������������������������������������������������ 265
Debugging Techniques and Tools���������������������������������������������������������������������������������������������� 267
Logging�������������������������������������������������������������������������������������������������������������������������������� 267
Dumping and Die Statements���������������������������������������������������������������������������������������������� 269
Exception Handling�������������������������������������������������������������������������������������������������������������� 271
IDE Debugging Tools������������������������������������������������������������������������������������������������������������ 273
Chrome DevTools����������������������������������������������������������������������������������������������������������������� 274
Performance Monitoring with Laravel Telescope���������������������������������������������������������������������� 274
Installation��������������������������������������������������������������������������������������������������������������������������� 274
Enabling Telescope�������������������������������������������������������������������������������������������������������������� 277
Identifying and Resolving Performance Bottlenecks���������������������������������������������������������������� 278
Monitoring and Profiling������������������������������������������������������������������������������������������������������ 278
Identify Bottlenecks������������������������������������������������������������������������������������������������������������� 278
Query Optimization�������������������������������������������������������������������������������������������������������������� 279
Caching�������������������������������������������������������������������������������������������������������������������������������� 279
Code Optimization��������������������������������������������������������������������������������������������������������������� 279
Use Queues for Background Processing����������������������������������������������������������������������������� 279
Profiling and Benchmarking������������������������������������������������������������������������������������������������ 280
Load Testing������������������������������������������������������������������������������������������������������������������������ 280
Optimize Asset Delivery������������������������������������������������������������������������������������������������������� 280
Scalability and Infrastructure���������������������������������������������������������������������������������������������� 280
Monitoring and Optimizing Application Security����������������������������������������������������������������������� 280
Keep Dependencies Up to Date������������������������������������������������������������������������������������������� 281
Implement Secure Authentication��������������������������������������������������������������������������������������� 281
Protect Routes and Sensitive Data�������������������������������������������������������������������������������������� 281
Sanitize and Validate User Input������������������������������������������������������������������������������������������ 281
Implement CSRF Protection������������������������������������������������������������������������������������������������� 281

xiv
Table of Contents

Secure Database Access����������������������������������������������������������������������������������������������������� 282


Implement Content Security Policies (CSPs)����������������������������������������������������������������������� 282
Protect Against Cross-Site Scripting (XSS)�������������������������������������������������������������������������� 282
Log and Monitor Security Events����������������������������������������������������������������������������������������� 282
Perform Security Audits and Penetration Testing���������������������������������������������������������������� 282
Educate Developers and Users�������������������������������������������������������������������������������������������� 283
Stay Updated with Security Practices��������������������������������������������������������������������������������� 283
Summary���������������������������������������������������������������������������������������������������������������������������������� 283

Chapter 13: Scaling Laravel Applications������������������������������������������������������������� 285


Scaling Strategies and Considerations������������������������������������������������������������������������������������� 286
Caching�������������������������������������������������������������������������������������������������������������������������������� 286
Database Optimization�������������������������������������������������������������������������������������������������������� 287
Queue System��������������������������������������������������������������������������������������������������������������������� 288
Monitoring and Scaling Metrics������������������������������������������������������������������������������������������� 288
Auto-scaling������������������������������������������������������������������������������������������������������������������������ 289
Caching HTTP Responses���������������������������������������������������������������������������������������������������� 290
Code Optimization��������������������������������������������������������������������������������������������������������������� 291
Load Balancing and Horizontal Scaling������������������������������������������������������������������������������������� 291
Load Balancing�������������������������������������������������������������������������������������������������������������������� 292
Horizontal Scaling��������������������������������������������������������������������������������������������������������������� 293
Database Scaling Techniques��������������������������������������������������������������������������������������������������� 294
Vertical Scaling�������������������������������������������������������������������������������������������������������������������� 295
Database Replication����������������������������������������������������������������������������������������������������������� 295
Database Sharding�������������������������������������������������������������������������������������������������������������� 296
Database Partitioning���������������������������������������������������������������������������������������������������������� 297
Database Caching���������������������������������������������������������������������������������������������������������������� 298
Caching and Content Delivery Networks (CDNs)����������������������������������������������������������������������� 299
Caching�������������������������������������������������������������������������������������������������������������������������������� 299
Content Delivery Networks (CDNs)�������������������������������������������������������������������������������������� 300
Implementing Queue Workers for High Traffic�������������������������������������������������������������������������� 303

xv
Table of Contents

Set Up the Queue Connection���������������������������������������������������������������������������������������������� 303


Using Docker Compose������������������������������������������������������������������������������������������������������� 305
Summary���������������������������������������������������������������������������������������������������������������������������������� 307

Chapter 14: Advanced Error Handling and Exception Management��������������������� 309


Customizing Error Pages and Handling Exceptions������������������������������������������������������������������ 310
Error Handling and Exception Management������������������������������������������������������������������������ 310
Overview of PHP Exceptions and Laravel’s Exception Handling Mechanism
Using Try-Catch Blocks�������������������������������������������������������������������������������������������������������� 311
Handling Exceptions in Laravel������������������������������������������������������������������������������������������� 313
Creating Custom Exception Classes and Throwing Exceptions to Manage
Specific Error Scenarios Effectively������������������������������������������������������������������������������������ 315
Customizing Error Pages����������������������������������������������������������������������������������������������������� 317
Demonstrating User-Friendly Error Pages with Relevant Information and Helpful
Instructions�������������������������������������������������������������������������������������������������������������������������� 319
Exception Logging and Reporting��������������������������������������������������������������������������������������������� 321
Configuring Laravel’s Logging Mechanism to Record Exceptions in Various Channels
(e.g., File, Database, Syslog) for Effective Error Tracking����������������������������������������������������� 321
Best Practices for Logging Exceptions with Context-­Specific Information and
Timestamps������������������������������������������������������������������������������������������������������������������������� 324
Logging and Monitoring Application Errors������������������������������������������������������������������������������� 325
Logging in Laravel��������������������������������������������������������������������������������������������������������������� 325
Centralized Logging with Laravel���������������������������������������������������������������������������������������� 332
Monitoring Application Errors���������������������������������������������������������������������������������������������� 335
Implementing Error Reporting and Alerting Systems���������������������������������������������������������������� 340
Error Reporting with Notifications��������������������������������������������������������������������������������������� 340
Real-Time Error Reporting with WebSockets���������������������������������������������������������������������� 346
Debugging Production Errors with Remote Logging and Tracing���������������������������������������������� 354
Remote Logging������������������������������������������������������������������������������������������������������������������ 354
Distributed Tracing�������������������������������������������������������������������������������������������������������������� 355
Error Alerting and Monitoring���������������������������������������������������������������������������������������������� 356
Live Debugging Tools����������������������������������������������������������������������������������������������������������� 357
Log Analysis and Error Investigation����������������������������������������������������������������������������������� 357
Postmortem Analysis and Resolution���������������������������������������������������������������������������������� 358

xvi
Table of Contents

Error Recovery and Graceful Degradation Strategies��������������������������������������������������������������� 358


Graceful Degradation����������������������������������������������������������������������������������������������������������� 358
Implementing Retry Mechanisms���������������������������������������������������������������������������������������� 361
Circuit Breaker Pattern�������������������������������������������������������������������������������������������������������� 367
Summary���������������������������������������������������������������������������������������������������������������������������������� 371

Chapter 15: Building Internationalized Applications with Laravel����������������������� 373


Introduction to Internationalization (i18n) and Localization (l10n)�������������������������������������������� 374
Internationalization (i18n)���������������������������������������������������������������������������������������������������� 374
Localization (l10n)��������������������������������������������������������������������������������������������������������������� 375
Key Components of Internationalization and Localization in Laravel���������������������������������� 375
Configuring Language Files and Translation Strings����������������������������������������������������������������� 376
Understanding Language Files�������������������������������������������������������������������������������������������� 376
Creating Language Files������������������������������������������������������������������������������������������������������ 376
Writing Translation Strings�������������������������������������������������������������������������������������������������� 377
Translating Database Content and User Input��������������������������������������������������������������������������� 379
Translating Database Content���������������������������������������������������������������������������������������������� 379
Create a Migration for the Translation Table������������������������������������������������������������������������ 380
Managing Locale-Specific Views and Assets���������������������������������������������������������������������������� 384
Organizing Locale-Specific Views��������������������������������������������������������������������������������������� 384
Handling Locale-Specific Assets����������������������������������������������������������������������������������������� 385
Localization of Asset URLs��������������������������������������������������������������������������������������������������� 386
Implementing Multilingual URLs and URL Routing�������������������������������������������������������������������� 387
Setting Up Multilingual Routes�������������������������������������������������������������������������������������������� 387
Generating Multilingual URLs���������������������������������������������������������������������������������������������� 389
Language Switching������������������������������������������������������������������������������������������������������������ 389
Summary���������������������������������������������������������������������������������������������������������������������������������� 390

Chapter 16: Advanced Frontend Development with Laravel��������������������������������� 391


Integrating Laravel with Modern Frontend Frameworks����������������������������������������������������������� 392
React����������������������������������������������������������������������������������������������������������������������������������� 392
Vue.js����������������������������������������������������������������������������������������������������������������������������������� 393

xvii
Table of Contents

Setting Up Laravel��������������������������������������������������������������������������������������������������������������� 394


Authentication and Authorization���������������������������������������������������������������������������������������� 410
Building Single-Page Applications (SPAs) with Laravel and JavaScript������������������������������������ 414
Set Up the Laravel Backend������������������������������������������������������������������������������������������������ 414
Enhancing User Experience with AJAX and Vue.js Components����������������������������������������������� 416
Install Vue.js������������������������������������������������������������������������������������������������������������������������� 417
Implementing Real-Time Updates with Laravel Echo and WebSockets������������������������������������ 420
Summary���������������������������������������������������������������������������������������������������������������������������������� 424

Chapter 17: Advanced Database Techniques and Optimization��������������������������� 425


Database Indexing and Query Optimization Techniques����������������������������������������������������������� 426
Database Indexing��������������������������������������������������������������������������������������������������������������� 427
Query Optimization�������������������������������������������������������������������������������������������������������������� 428
Additional Techniques���������������������������������������������������������������������������������������������������������� 430
Advanced Database Relationships and Performance Considerations��������������������������������������� 433
Types of Relationships��������������������������������������������������������������������������������������������������������� 434
Optimization Techniques����������������������������������������������������������������������������������������������������� 434
Implementing Database Replication and Failover Strategies��������������������������������������������������� 435
Database Replication����������������������������������������������������������������������������������������������������������� 435
Failover Strategies��������������������������������������������������������������������������������������������������������������� 437
Amazon RDS Multi-AZ with One Standby���������������������������������������������������������������������������� 438
Amazon RDS Multi-AZ with Two Readable Standbys���������������������������������������������������������� 440
Tip for Failover and Replication with AWS RDS������������������������������������������������������������������� 444
Database Partitioning and Sharding for Large-Scale Applications������������������������������������������� 444
Database Partitioning���������������������������������������������������������������������������������������������������������� 445
Database Sharding�������������������������������������������������������������������������������������������������������������� 446
Considerations��������������������������������������������������������������������������������������������������������������������� 448
Data Migrations and Schema Management in Production Environments��������������������������������� 449
Data Migrations������������������������������������������������������������������������������������������������������������������� 449
Schema Management��������������������������������������������������������������������������������������������������������� 451
Summary���������������������������������������������������������������������������������������������������������������������������������� 453

xviii
Table of Contents

Chapter 18: Laravel and Serverless Computing��������������������������������������������������� 455


Introduction to Serverless Architecture and Function as a Service (FaaS)������������������������������� 456
The Benefits of Serverless Architecture and FaaS�������������������������������������������������������������� 456
Integrating Laravel with Serverless Platforms�������������������������������������������������������������������������� 458
Serverless Providers����������������������������������������������������������������������������������������������������������� 458
Decompose Your Laravel Application����������������������������������������������������������������������������������� 459
Scaling Laravel with Serverless Auto-scaling and Event Triggers�������������������������������������������� 461
Serverless Auto-scaling������������������������������������������������������������������������������������������������������� 461
The Benefits of Serverless Auto-scaling for Laravel����������������������������������������������������������� 462
To Take Advantage of Serverless Auto-scaling�������������������������������������������������������������������� 462
Event Triggers and Background Jobs���������������������������������������������������������������������������������� 464
Load Testing and Performance Optimization����������������������������������������������������������������������� 467
Monitoring and Debugging Serverless Laravel Applications����������������������������������������������������� 469
Serverless Monitoring Tools������������������������������������������������������������������������������������������������ 469
Summary���������������������������������������������������������������������������������������������������������������������������������� 475

Chapter 19: Building Progressive Web Applications (PWAs) with Laravel����������� 477
Understanding Progressive Web Applications and Service Workers����������������������������������������� 478
Key Characteristics of Progressive Web Applications���������������������������������������������������������� 479
Service Workers������������������������������������������������������������������������������������������������������������������ 479
Converting Laravel Applications into PWAs������������������������������������������������������������������������������� 480
Set Up a Manifest File��������������������������������������������������������������������������������������������������������� 480
Offline Support and Caching Strategies for PWAs�������������������������������������������������������������������� 484
Offline Support�������������������������������������������������������������������������������������������������������������������� 485
Caching Strategies�������������������������������������������������������������������������������������������������������������� 486
Push Notifications and Background Sync in PWAs������������������������������������������������������������������� 488
Push Notifications��������������������������������������������������������������������������������������������������������������� 488
Background Sync���������������������������������������������������������������������������������������������������������������� 489
Optimizing PWAs for Performance and User Experience���������������������������������������������������������� 491
Performance Auditing���������������������������������������������������������������������������������������������������������� 491
Code Splitting���������������������������������������������������������������������������������������������������������������������� 491
Lazy Loading������������������������������������������������������������������������������������������������������������������������ 492

xix
Table of Contents

Responsive Design�������������������������������������������������������������������������������������������������������������� 492


Minify and Compress Assets����������������������������������������������������������������������������������������������� 492
Cache Control Headers�������������������������������������������������������������������������������������������������������� 493
Offline Page������������������������������������������������������������������������������������������������������������������������� 493
Optimize Images������������������������������������������������������������������������������������������������������������������ 494
Background Data Sync�������������������������������������������������������������������������������������������������������� 494
PWA-Specific Caching Strategies���������������������������������������������������������������������������������������� 494
Optimize Fonts��������������������������������������������������������������������������������������������������������������������� 495
Use Web Workers����������������������������������������������������������������������������������������������������������������� 495
Monitor Performance����������������������������������������������������������������������������������������������������������� 496
Summary���������������������������������������������������������������������������������������������������������������������������������� 496

Chapter 20: Advanced UI/UX Design Patterns for Laravel������������������������������������ 497


Designing User-Friendly Interfaces with Laravel’s Blade Templating Engine��������������������������� 498
Organizing Blade Templates������������������������������������������������������������������������������������������������ 499
Using Template Inheritance (Extends)��������������������������������������������������������������������������������� 499
Using Partials (Includes)������������������������������������������������������������������������������������������������������ 500
Blade Directives for Conditionals and Loops����������������������������������������������������������������������� 501
Blade Components (Laravel 7+)������������������������������������������������������������������������������������������ 501
Form Handling with Blade��������������������������������������������������������������������������������������������������� 502
Design Consistency������������������������������������������������������������������������������������������������������������� 502
Mobile-Friendly Design������������������������������������������������������������������������������������������������������� 502
Implementing Responsive Design and Mobile Optimization Techniques���������������������������������� 502
Use CSS Media Queries������������������������������������������������������������������������������������������������������� 503
Mobile-First Approach��������������������������������������������������������������������������������������������������������� 503
Use Responsive Frameworks���������������������������������������������������������������������������������������������� 504
Optimize Images������������������������������������������������������������������������������������������������������������������ 504
Touch-Friendly Interactions������������������������������������������������������������������������������������������������� 505
Accessibility Considerations������������������������������������������������������������������������������������������������ 505
Viewport Meta Tag��������������������������������������������������������������������������������������������������������������� 505
Performance Optimization��������������������������������������������������������������������������������������������������� 505
Test on Various Devices������������������������������������������������������������������������������������������������������� 506

xx
Table of Contents

Enhancing User Experience with CSS Animation and Transition Effects���������������������������������� 506
CSS Animations������������������������������������������������������������������������������������������������������������������� 506
CSS Transitions�������������������������������������������������������������������������������������������������������������������� 507
Keyframe Animations���������������������������������������������������������������������������������������������������������� 507
Delicate Hover Effects��������������������������������������������������������������������������������������������������������� 508
CSS Transitions for Smooth State Changes������������������������������������������������������������������������� 508
Animation Timing Functions������������������������������������������������������������������������������������������������ 509
Use Animations Sparingly���������������������������������������������������������������������������������������������������� 509
Designing Accessible Applications with Laravel����������������������������������������������������������������������� 509
Semantic HTML������������������������������������������������������������������������������������������������������������������� 510
ARIA Roles and Attributes���������������������������������������������������������������������������������������������������� 510
Focus Management������������������������������������������������������������������������������������������������������������� 511
Alternative Text for Images�������������������������������������������������������������������������������������������������� 511
Form Accessibility��������������������������������������������������������������������������������������������������������������� 511
Color Contrast���������������������������������������������������������������������������������������������������������������������� 511
Test with Assistive Technologies����������������������������������������������������������������������������������������� 512
Accessibility Auditing Tools������������������������������������������������������������������������������������������������� 512
Provide Transcripts and Captions���������������������������������������������������������������������������������������� 512
Implementing User Feedback and Usability Testing in Laravel Applications���������������������������� 512
Feedback Collection Mechanisms��������������������������������������������������������������������������������������� 512
Error Reporting�������������������������������������������������������������������������������������������������������������������� 513
Analyze User Behavior��������������������������������������������������������������������������������������������������������� 513
Usability Testing������������������������������������������������������������������������������������������������������������������ 514
User Surveys����������������������������������������������������������������������������������������������������������������������� 514
Feedback Analysis and Action Plan������������������������������������������������������������������������������������� 515
Iterative Improvement��������������������������������������������������������������������������������������������������������� 515
Accessibility Testing������������������������������������������������������������������������������������������������������������ 515
Performance Testing������������������������������������������������������������������������������������������������������������ 515
User Support and Communication��������������������������������������������������������������������������������������� 515
Bug Tracking and Issue Management��������������������������������������������������������������������������������� 515
Summary���������������������������������������������������������������������������������������������������������������������������������� 516

xxi
Table of Contents

Chapter 21: Advanced Analytics and Reporting in Laravel���������������������������������� 517


Integrating Analytics Tools with Laravel������������������������������������������������������������������������������������ 518
Let’s Explore How to Integrate Google Analytics with Laravel��������������������������������������������� 519
Collecting and Analyzing Application Metrics and User Behavior��������������������������������������������� 521
Logging�������������������������������������������������������������������������������������������������������������������������������� 521
Custom Event Listeners������������������������������������������������������������������������������������������������������� 522
Database Queries���������������������������������������������������������������������������������������������������������������� 522
User Tracking and Cookies�������������������������������������������������������������������������������������������������� 523
Third-Party APIs������������������������������������������������������������������������������������������������������������������� 523
Analyzing the Data��������������������������������������������������������������������������������������������������������������� 524
Improving User Experience�������������������������������������������������������������������������������������������������� 524
Building Custom Dashboards and Reports with Laravel����������������������������������������������������������� 524
Define Dashboard Requirements����������������������������������������������������������������������������������������� 525
Set Up a Laravel Project������������������������������������������������������������������������������������������������������ 525
Design the Database Schema��������������������������������������������������������������������������������������������� 526
Seed the Database with Sample Data��������������������������������������������������������������������������������� 527
Create Routes and Controllers��������������������������������������������������������������������������������������������� 528
Create Dashboard and Report Views����������������������������������������������������������������������������������� 529
Styling and Enhancements�������������������������������������������������������������������������������������������������� 530
Authentication and Authorization���������������������������������������������������������������������������������������� 530
Deploy the Dashboard��������������������������������������������������������������������������������������������������������� 530
Implementing A/B Testing and Conversion Tracking����������������������������������������������������������������� 530
Using Data Visualization Libraries with Laravel������������������������������������������������������������������������ 533
Summary���������������������������������������������������������������������������������������������������������������������������������� 536

Chapter 22: Advanced Third-Party Integrations��������������������������������������������������� 537


Integrating Laravel with Payment Gateways����������������������������������������������������������������������������� 538
Implementing Social Media and Authentication (OAuth) Integrations��������������������������������������� 543
Integrating Laravel with Email Marketing Services������������������������������������������������������������������ 545
Integrating Laravel with Cloud Storage Providers��������������������������������������������������������������������� 548
Building Custom API Integrations with Laravel������������������������������������������������������������������������� 550
Summary���������������������������������������������������������������������������������������������������������������������������������� 554
xxii
Table of Contents

Chapter 23: Securing Laravel Applications���������������������������������������������������������� 555


Implementing Two-Factor Authentication (2FA) in Laravel�������������������������������������������������������� 556
Here’s How 2FA Typically Works������������������������������������������������������������������������������������������ 557
To Enable 2FA in Laravel, You Can Follow These Steps������������������������������������������������������� 558
Securing User Input and Form Validation���������������������������������������������������������������������������������� 563
Use Laravel’s Validation Rules��������������������������������������������������������������������������������������������� 563
Preventing Cross-Site Scripting (XSS) and Cross-­Site Request Forgery (CSRF) Attacks���������� 566
Preventing Cross-Site Scripting (XSS) Attacks�������������������������������������������������������������������� 566
Preventing Cross-Site Request Forgery (CSRF) Attacks������������������������������������������������������ 567
Securing API Endpoints with API Keys and Rate Limiting��������������������������������������������������������� 568
Securing API Endpoints with API Keys��������������������������������������������������������������������������������� 568
Securing API Endpoints with Rate Limiting������������������������������������������������������������������������� 569
Implementing Content Security Policies (CSPs) and SSL/TLS Encryption�������������������������������� 571
The Main Goals of the Content Security Policy�������������������������������������������������������������������� 571
Implementing Content Security Policies (CSPs)������������������������������������������������������������������ 572
SSL/TLS Standard���������������������������������������������������������������������������������������������������������������� 573
Self-Signed Certificates������������������������������������������������������������������������������������������������������� 575
Summary���������������������������������������������������������������������������������������������������������������������������������� 577

Chapter 24: Advanced DevOps and Infrastructure Automation���������������������������� 579


Infrastructure as Code (IaC) with Laravel and Tools like Terraform������������������������������������������� 580
Here’s How Terraform Plan Acts as an Advisory������������������������������������������������������������������ 581
To Use Terraform with Laravel, You Would Typically������������������������������������������������������������ 582
To Perform a Destroy Operation (e.g., Removing Resources)���������������������������������������������� 583
Setting Up Terraform for Laravel����������������������������������������������������������������������������������������� 583
Steps to Set Up Terraform for Your Laravel IaC������������������������������������������������������������������� 583
Automating Deployment Pipelines with Laravel and CI/CD Tools���������������������������������������������� 587
Implementing Application Monitoring and Log Management��������������������������������������������������� 590
Application Monitoring�������������������������������������������������������������������������������������������������������� 592
Log Management����������������������������������������������������������������������������������������������������������������� 592

xxiii
Table of Contents

Continuous Performance Optimization and Auto-scaling��������������������������������������������������������� 594


Continuous Performance Optimization�������������������������������������������������������������������������������� 594
Auto-scaling������������������������������������������������������������������������������������������������������������������������ 595
Building Highly Available and Fault-Tolerant Laravel Infrastructures��������������������������������������� 596
Components of a Highly Available and Fault-Tolerant Laravel Infrastructure���������������������� 596
Web Application Layer��������������������������������������������������������������������������������������������������������� 599
Load Balancing�������������������������������������������������������������������������������������������������������������������� 600
Database Layer�������������������������������������������������������������������������������������������������������������������� 600
Caching�������������������������������������������������������������������������������������������������������������������������������� 601
File Storage������������������������������������������������������������������������������������������������������������������������� 601
Content Delivery������������������������������������������������������������������������������������������������������������������ 602
Monitoring and Logging������������������������������������������������������������������������������������������������������� 602
Security������������������������������������������������������������������������������������������������������������������������������� 602
Backup and Disaster Recovery�������������������������������������������������������������������������������������������� 603
Logging and Error Tracking�������������������������������������������������������������������������������������������������� 603
Summary���������������������������������������������������������������������������������������������������������������������������������� 604

Chapter 25: New Features and Updates in Laravel 10������������������������������������������ 605


The Central Role of PHP 8.1 in Laravel 10��������������������������������������������������������������������������������� 605
Readonly Properties������������������������������������������������������������������������������������������������������������������ 605
Array Is List������������������������������������������������������������������������������������������������������������������������������� 606
Enhancements to Laravel’s Official Packages�������������������������������������������������������������������������� 607
Improved Predis Version Compatibility������������������������������������������������������������������������������������� 609
Native Type Declarations����������������������������������������������������������������������������������������������������������� 609
Default Invokable Validation Rules�������������������������������������������������������������������������������������������� 611
Enhanced Database Operations with Native Column Modification Support����������������������������� 612
Native Retrieval of Column Types���������������������������������������������������������������������������������������������� 613
Enhanced Support for the whereExists() Method in the Eloquent Builder�������������������������������� 615
Optimizing Eager Loading��������������������������������������������������������������������������������������������������������� 616
$path Is Optional for Filesystem Methods�������������������������������������������������������������������������������� 617
Enhanced Database Expressions and Grammar-Specific Formatting��������������������������������������� 618

xxiv
Table of Contents

Enhanced SQL Server Query Performance with FETCH and OFFSET for Queries Without
orderBy������������������������������������������������������������������������������������������������������������������������������������� 620
Laravel Pennant������������������������������������������������������������������������������������������������������������������������ 621
Laravel Process Interaction������������������������������������������������������������������������������������������������������� 622
Pest Scaffolding������������������������������������������������������������������������������������������������������������������������ 624
Summary���������������������������������������������������������������������������������������������������������������������������������� 624

Index��������������������������������������������������������������������������������������������������������������������� 625

xxv
About the Author
Sivaraj Selvaraj’s work is focused on modern technologies
and industry best practices. His experience includes
frontend development approaches such as HTML5, CSS3,
and JavaScript frameworks, as well as creating responsive
web design to optimize user experience across devices. He
specializes in developing dynamic web applications with
server-side languages such as PHP, WordPress, and Laravel,
as well as managing and integrating databases with SQL and
MySQL. Sivaraj is enthusiastic about sharing his significant
expertise and experience, empowering readers to solve tough challenges and create
highly functional, visually appealing websites.

xxvii
About the Technical Reviewer
Yogesh Kamal Sharma is an application developer
enthusiast, consultant, and avid paperback reader. He is
presently associated with NICE Actimize to modernize
AML programs by bringing together machine learning and
domain expertise to combat money laundering and terrorist
financing. He graduated from VSIT Mumbai, is a father of
one, and enjoys his free time golfing.

xxix
Acknowledgments
I am indebted to my mentors and fellow developers in the Laravel community. Your
guidance, insights, and shared knowledge have been pivotal in my growth as a Laravel
developer. The open collaboration and spirit of learning in the community have inspired
me to strive for continuous improvement.
I extend my gratitude to the reviewers and editors who diligently reviewed and
refined the content, ensuring its accuracy and clarity.
To my friend Divya Modi, thank you for your unwavering camaraderie and
encouragement throughout this journey. Your insights and discussions have enriched
my understanding of book development as a whole.
To all the readers and supporters of this book, thank you for your interest in learning
and mastering Laravel. Your passion for growth and dedication to honing your skills
motivate me to share my knowledge and experiences.
This book would not have been possible without the contributions of each individual
mentioned here. Your belief in this project and your unwavering support have been
integral to its success.
With sincere appreciation

xxxi
Introduction
Welcome to Building Real-Time Marvels with Laravel: Create Dynamic and Interactive
Web Applications. This book will introduce you to the exciting world of Laravel, a
powerful PHP framework that allows developers to create cutting-edge web apps with
real-time functionality. Whether you’re a seasoned developer or just starting out, this
thorough tutorial will provide you with the knowledge and skills you need to create
remarkable and engaging web experiences with Laravel.
Because of its elegance, simplicity, and feature-rich environment, Laravel has
garnered enormous appeal in the online development community. It gives developers a
strong collection of tools and conventions that help streamline the development process,
letting them focus on creating novel features and great user experiences.
We will cover the Laravel framework in a logical and organized manner, chapter by
chapter, throughout this book. Each chapter delves further into the Laravel environment,
covering fundamental principles, advanced techniques, and best practices to help you
become an expert Laravel developer.
Our goal is to provide you with the knowledge and confidence you need to create
real-time miracles—online applications that engage users with dynamic information,
interactive interfaces, and seamless communication. This book will walk you through
the process of creating a real-time chat application, a collaborative dashboard that
displays real-time data, or any other interactive online application.
If you’re new to Laravel, don’t worry! We’ll start with an overview of the Laravel
ecosystem, covering its key principles, architecture, and vital components. You will learn
how to configure your development environment so that you have everything you need
to begin developing Laravel applications.
Fear not, those who are already familiar with Laravel! There are numerous advanced
topics available to challenge and extend your knowledge. This book covers a wide
range of subjects, from learning complicated routing strategies to fine-tuning database
interactions with Eloquent Object-Relational Mapping (ORM) to adding real-time
features with WebSockets to improving performance and scaling your applications.
Throughout the journey, you will experience practical examples, real-world use
cases, and hands-on exercises to help you understand the ideas covered. Each chapter

xxxiii
Introduction

builds on the one before it, steadily increasing the level of intricacy of the topics
discussed. By the end of this book, you will have the knowledge and confidence to create
sophisticated online applications that will astound users and advance your Laravel
developer career.
So whether you are a curious beginner or a seasoned developer seeking to unlock the
full potential of Laravel, fasten your seatbelt as we embark on this exhilarating journey of
building real-time marvels with Laravel. Let’s dive in!

What Is in This Book?


In this book, Building Real-Time Marvels with Laravel: Create Dynamic and Interactive
Web Applications, you will

• Master Laravel’s fundamentals and set up your development


environment

• Explore advanced routing techniques and database management


with Eloquent ORM

• Implement user authentication, authorization, and Application


Programming Interface (API) building with Laravel

• Learn real-time application development with WebSockets and


Laravel Echo

• Enhance performance with caching, optimize database queries, and


scale Laravel applications

Throughout the book, you’ll find practical examples of testing, security, and
integration with third-party services, empowering you to build impressive real-time web
applications using Laravel.

Development Environment
The development environment for this book includes
• PHP and Composer for the Laravel framework

• A web server (e.g., Apache or Nginx)

xxxiv
Introduction

• A database (e.g., MySQL or SQLite)

• An integrated development environment (IDE) (e.g., Visual


Studio Code)

• Git for version control

• Laravel’s built-in local development server

Chapters at a Glance
Chapter 1, “Understanding the Laravel Ecosystem”: In this introductory chapter, we’ll
take a closer look at the Laravel framework, learning its key features, architecture, and
philosophy that make it stand out among other PHP frameworks. You’ll discover how to
set up your development environment and get ready to embark on a journey through the
Laravel ecosystem.
Chapter 2, “Advanced Routing Techniques”: Routing is a fundamental aspect of any
web application, and Laravel provides a robust routing system. In this chapter, we’ll
delve into advanced routing techniques, such as working with route parameters and
wildcards, route model binding, and route caching. You’ll also explore how to group
routes using middleware to enhance code organization and maintainability.
Chapter 3, “Database Management and Eloquent ORM”: A crucial part of web
application development is managing databases effectively. Laravel’s Eloquent ORM
simplifies database interaction and makes querying and relationship management a
breeze. We’ll explore database migrations, learn how to create and modify tables, and
dive deep into Eloquent relationships, including one-to-one, one-to-many, and many-
to-­many relationships.
Chapter 4, “Authentication and Authorization”: Security is paramount in any web
application. In this chapter, we’ll cover user authentication, including registration, login,
and logout functionality. Additionally, you’ll learn how to implement authorization, user
roles, and permissions using Laravel’s robust authentication and authorization systems.
Chapter 5, “Building APIs with Laravel”: APIs play a vital role in modern web
application development. In this chapter, we’ll explore the world of API development
with Laravel, including building RESTful APIs. You’ll discover how to handle API
authentication and security, rate limiting, and effective error handling to create robust
and reliable API endpoints.

xxxv
Introduction

Chapter 6, “Caching and Performance Optimization”: Performance is a critical


aspect of web applications, and Laravel offers powerful caching mechanisms to improve
response times. In this chapter, we’ll explore Laravel’s cache system, learn to implement
caching using Redis and Memcached, and discuss cache tagging and cache invalidation
strategies. Additionally, you’ll discover performance optimization techniques to speed
up your Laravel applications.
Chapter 7, “Advanced Middleware Techniques”: Middleware plays a vital role in
request processing and application logic. In this chapter, we’ll go beyond the basics
and explore creating custom middleware, understanding the middleware pipeline, and
implementing terminable middleware. You’ll also learn about middleware parameters
and dependencies, along with best practices and performance considerations.
Chapter 8, “Real-Time Applications with Laravel”: Real-time features can
significantly enhance user experiences. This chapter introduces you to real-time
application development with Laravel. We’ll explore Laravel WebSockets, Laravel Echo
for broadcasting events, and building real-time notifications and chat applications.
Chapter 9, “Testing and Test-Driven Development”: Testing is a crucial aspect of
building robust and reliable applications. In this chapter, you’ll learn the fundamentals
of testing in Laravel, including writing unit tests with PHPUnit and testing HTTP requests
and responses. We’ll also dive into the Test-Driven Development (TDD) workflow,
ensuring that your applications are thoroughly tested and bug-free.
Chapter 10, “Queues and Job Scheduling”: Laravel’s queuing system enables
asynchronous processing of tasks, making your application more scalable and efficient.
This chapter introduces you to queues and workers, setting up queue drivers and
connections, creating and dispatching jobs, and managing failed jobs and retries. You’ll
also explore Laravel’s task scheduler for automating routine tasks.
Chapter 11, “Advanced Package Development”: Laravel’s robust package
development system allows you to create reusable and distributable components. In this
chapter, we’ll dive into package development, learn to create custom service providers,
publish configuration and assets, and test and version your packages for distribution.
Chapter 12, “Performance Monitoring and Debugging”: Monitoring the performance
of your Laravel applications is essential for identifying bottlenecks and improving
efficiency. In this chapter, we’ll explore profiling Laravel applications, debugging
techniques, and leveraging Laravel Telescope for performance monitoring. We’ll also
discuss best practices for logging and monitoring application errors.

xxxvi
Introduction

Chapter 13, “Scaling Laravel Applications”: As your application grows, scalability


becomes crucial. In this chapter, we’ll discuss scaling strategies and considerations,
load balancing, horizontal scaling, and database scaling techniques. We’ll also explore
caching and Content Delivery Networks (CDNs) for better performance.
Chapter 14, “Advanced Error Handling and Exception Management”: Effective error
handling is crucial for maintaining the stability of your application. In this chapter, you’ll
learn how to customize error pages and handle exceptions gracefully. We’ll explore
logging and monitoring application errors, implementing error reporting and alerting
systems, and debugging production errors with remote logging and tracing.
Chapter 15, “Building Internationalized Applications with Laravel”: As the world
becomes more interconnected, building internationalized applications is essential. In
this chapter, we’ll introduce you to internationalization and localization in Laravel. You’ll
learn to configure language files, translate database content and user input, and manage
locale-specific views and assets.
Chapter 16, “Advanced Frontend Development with Laravel”: Seamless integration
between the backend and frontend is vital for modern web applications. In this chapter,
we’ll explore integrating Laravel with modern frontend frameworks, building single-page
applications (SPAs) using Laravel and JavaScript, enhancing the user experience with
Asynchronous JavaScript and XML (AJAX) and Vue.js components, and implementing
real-time updates with Laravel Echo and WebSockets.
Chapter 17, “Advanced Database Techniques and Optimization”: Databases are
the heart of most web applications, and optimizing database performance is crucial
for a seamless user experience. In this chapter, we’ll delve into database indexing,
query optimization techniques, advanced database relationships, and performance
considerations. You’ll also learn about implementing database replication and failover
strategies for high availability.
Chapter 18, “Laravel and Serverless Computing”: Serverless architecture is gaining
popularity for its scalability and cost-efficiency. In this chapter, you’ll explore integrating
Laravel with serverless platforms, leveraging Function as a Service (FaaS), and scaling
Laravel applications with serverless autoscaling and event triggers. We’ll also cover
monitoring and debugging serverless Laravel applications.
Chapter 19, “Building Progressive Web Applications (PWAs) with Laravel”: Building
PWAs with Laravel provides an enhanced user experience, especially on mobile devices.
In this chapter, you’ll learn about PWAs and service workers, converting Laravel

xxxvii
Introduction

applications into PWAs, and implementing offline support and caching strategies. We’ll
also explore push notifications and background sync for improved user engagement.
Chapter 20, “Advanced UI/UX Design Patterns for Laravel”: The user interface
and user experience are critical for the success of your application. In this chapter,
you’ll discover how to design user-friendly interfaces with Laravel’s Blade templating
engine, implement responsive design and mobile optimization techniques, enhance
the user experience with CSS animation and transition effects, and design accessible
applications. We’ll also cover user feedback and usability testing in Laravel applications.
Chapter 21, “Advanced Analytics and Reporting in Laravel”: Understanding user
behavior and application performance is essential for making informed decisions. In this
chapter, you’ll explore integrating analytics tools with Laravel, collecting and analyzing
application metrics and user behavior, building custom dashboards and reports,
and implementing A/B testing and conversion tracking. We’ll also discuss using data
visualization libraries with Laravel.
Chapter 22, “Advanced Third-Party Integrations”: Modern web applications often
rely on third-party services for payment processing, authentication, and more. In
this chapter, you’ll explore integrating Laravel with payment gateways, implementing
social media and authentication (OAuth) integrations, connecting Laravel with email
marketing services, integrating Laravel with cloud storage providers, and building
custom API integrations.
Chapter 23, “Securing Laravel Applications”: Security is a top priority in web
application development. In this chapter, you’ll learn how to implement two-factor
authentication (2FA) in Laravel, secure user input and form validation, prevent Cross-
Site Scripting (XSS) and Cross-Site Request Forgery (CSRF) attacks, and secure API
endpoints with API keys and rate limiting. We’ll also explore implementing Content
Security Policies (CSPs) and Secure Sockets Layer/ Transport Layer Security (SSL/TLS)
encryption for enhanced security.
Chapter 24, “Advanced DevOps and Infrastructure Automation”: Automating
infrastructure management and deployment pipelines is essential for efficient
development workflows. In this chapter, you’ll explore Infrastructure as Code (IaC) with
Laravel and tools like Terraform, automating deployment pipelines with Laravel and CI/
CD tools, implementing application monitoring and log management, and continuous
performance optimization and auto-scaling. We’ll also discuss building highly available
and fault-tolerant Laravel infrastructures.

xxxviii
Introduction

Chapter 25, “New Features and Updates in Laravel 10”: Laravel is continuously
evolving, introducing new features and improvements with each release. In this final
chapter, we’ll explore the latest updates in Laravel, ensuring you stay up to date with the
cutting-edge technologies and tools available for building real-time marvels.
Each chapter is thoughtfully crafted to equip you with practical knowledge and
real-world skills that you can immediately apply to your own projects. Throughout the
book, we provide hands-on examples and code snippets, ensuring you gain a clear
understanding of the topics covered.
Prepare to unlock the full potential of Laravel and embark on a journey of building
real-time marvels that leave a lasting impression on your users. Let’s get started!

xxxix
CHAPTER 1

Understanding the Laravel


Ecosystem
Welcome to this comprehensive guide to the Laravel framework. In this chapter, we
will embark on a journey to explore the various aspects of the Laravel ecosystem,
gaining insights into one of the most popular and powerful PHP frameworks in the web
development world.
Introduction to the Laravel Ecosystem
In this section, we will provide an overview of Laravel, delving into its history,
development philosophy, and rise to prominence in the web development community.
You'll gain a clear understanding of why Laravel has become the go-to choice for
developers seeking a robust and elegant solution for building web applications.
Setting Up the Development Environment
Before we dive into the depths of Laravel, it's essential to set up a proper
development environment. Here, we will walk you through the steps required to
configure your local environment for Laravel development, ensuring a smooth and
productive coding experience.
Key Concepts and Principles of Laravel
Laravel is built upon a set of core principles and concepts that make it unique and
efficient. In this section, we will explore these foundational ideas, such as the MVC
architecture, Eloquent ORM, routing, middleware, and more. Understanding these
concepts is crucial for harnessing the full potential of Laravel.
Exploring the Laravel Ecosystem
Laravel is more than just a framework; it comes with an extensive ecosystem of
packages, libraries, and tools that enhance its capabilities. In this section, we will take a
closer look at some of the most popular Laravel packages and extensions, demonstrating
how they can elevate your development process and make your projects even more
powerful.

1
© Sivaraj Selvaraj 2024
S. Selvaraj, Building Real-Time Marvels with Laravel, https://doi.org/10.1007/978-1-4842-9789-6_1
Chapter 1 Understanding the Laravel Ecosystem

Throughout this chapter, we aim to equip you with a solid understanding of the
Laravel ecosystem, setting the stage for deeper exploration and mastery in the chapters
to come. So let's begin this exciting journey into the world of Laravel!

Introduction to the Laravel Ecosystem


Taylor Otwell created Laravel in 2011 as an open source PHP web application framework.
It quickly gained popularity and is now one of the most popular choices for developing
modern web applications. Laravel simplifies and streamlines the web development
process with its expressive syntax, developer-friendly features, and elegant design.
The Laravel ecosystem extends beyond the core framework, offering a diverse
set of tools and libraries that enhance and supplement its functionality. Laravel
Mix for frontend asset compilation, Laravel Horizon for managing and monitoring
queues, Laravel Nova for building administration panels, and Laravel Passport for API
authentication are all part of the ecosystem. Furthermore, numerous community-driven
packages covering a wide range of functionalities and integrations are available through
platforms such as Packagist.
Laravel remains at the forefront of web development frameworks, making it a top
choice for developers that place a premium on project productivity, maintainability, and
scalability. Whether you are a novice or an experienced developer, the Laravel ecosystem
provides a comprehensive and powerful toolkit for quickly creating impressive web
applications. Figure 1-1 illustrates the Model-View-Controller (MVC) architectural
pattern.

Figure 1-1. MVC diagram

2
Chapter 1 Understanding the Laravel Ecosystem

MVC Pattern
Routes: Routes define the URLs and corresponding controller actions. They map
incoming requests to the appropriate controller method.
Controllers: Controllers handle user requests and manage the flow of data. They
receive input from users, interact with models, and return responses. Controllers contain
methods (actions) that define the logic for each route.
Models: Models represent the data and business logic of the application. They
interact with the database and provide an abstraction layer for retrieving, creating,
updating, and deleting data. Models encapsulate the application's data structure and
define relationships between entities.
Views: Views are responsible for presenting data to users. They contain the HTML
templates and UI components that render the final output. Views can access data from
models and controllers to display information.

Structure of the Framework


The ‘app’ directory contains the core application code, including console commands,
exception handlers, HTTP-related classes (controllers, middleware, requests, and
resources), and models.
The ‘bootstrap’ directory contains the bootstrap files responsible for bootstrapping
the Laravel application.
The ‘config’ directory contains configuration files for various aspects of the
application, such as database connections, caching, session management, etc.
The ‘database’ directory houses files related to the database, including factories
for generating dummy data, migrations for managing database schema changes, and
seeders for populating the database with initial data.
The ‘public’ directory serves as the document root for the application. It contains
the front controller (‘index.php’) and publicly accessible assets like CSS, JavaScript, and
image files.
The ‘resources’ directory holds non-PHP resources, including JavaScript files, CSS
stylesheets, and views (Blade templates) used for rendering HTML.
The ‘routes’ directory contains route definitions that map URLs to corresponding
controllers and actions.
The ‘storage’ directory is used for storing various types of data generated by the
application, such as uploaded files, cached data, logs, etc.

3
Chapter 1 Understanding the Laravel Ecosystem

The ‘tests’ directory houses the application's automated tests.


The ‘vendor’ directory contains the dependencies installed via Composer.
The ‘.env’ file stores environment-specific configuration settings.
The ‘artisan’ file is the command-line interface for interacting with the Laravel
application.
The ‘composer.json’ file defines the project's dependencies and provides metadata
about the application.
This structure is a standard layout for a Laravel application, although you may find
some additional files and directories depending on the specific requirements of your
project. Figure 1-2 illustrates the Laravel application structure diagram.

Figure 1-2. Laravel application structure diagram

4
Chapter 1 Understanding the Laravel Ecosystem

Its philosophy revolves around developer productivity, with a focus on reducing


repetitive tasks and providing convenient solutions for common web development
challenges.
One of the key strengths of Laravel is its vibrant and active community. The
community actively contributes to the framework by developing packages; sharing
knowledge through documentation, tutorials, and forums; and continuously improving
the overall Laravel ecosystem.

Setting Up the Development Environment


Before diving into Laravel development, it's essential to set up the development
environment. This involves installing the necessary software and tools to run
Laravel applications. Let's explore the steps involved in setting up the development
environment.

PHP (Hypertext Preprocessor)


PHP is a server-side scripting language for web development. It's commonly used to
build dynamic web pages and web apps. PHP code is run on the server, which generates
HTML, which is then transmitted to the client's web browser.

Install PHP
Download and install PHP 7.4 or higher from the official PHP website (www.php.net/
downloads.php). Verify the installation by running ‘php -v’ in the command prompt. You
should see the PHP version displayed.

Web Server
A web server is a piece of software that runs on a server computer and monitors
incoming HTTP requests from clients (web browsers). It processes these requests and
returns to the customers the necessary web pages or resources. Web servers that are
often used include Apache, Nginx, and Microsoft IIS.

5
Chapter 1 Understanding the Laravel Ecosystem

Install a Web Server


Configure the web server to serve PHP files. For example, in Apache, you can enable the
‘mod_php’ module. Verify the web server installation by accessing ‘http://localhost’ in
your web browser. You should see a default web page.

Database (DB)
A database is a systematic collection of data that has been arranged and stored in order
to be easily retrieved and manipulated. It is used to store and manage application data
such as user information, product details, and other information. Databases commonly
used in web development include MySQL, PostgreSQL, and SQLite.

Install a Database
Choose a database management system like MySQL, PostgreSQL, or SQLite and install it
on your machine. Create a new database for your Laravel application.
Configure the database connection in the Laravel ‘.env’ file.
For Illustration, refer to the following snippet:

---------------------------------------------------------------------------
     DB_CONNECTION=mysql
     DB_HOST=127.0.0.1
     DB_PORT=3306
     DB_DATABASE=your_database
     DB_USERNAME=your_username
     DB_PASSWORD=your_password
---------------------------------------------------------------------------

Composer
Composer is a PHP dependency management tool. It makes it easier to manage
PHP packages and libraries in your project. It lets you declare the libraries on which
your project depends and then installs and updates them automatically, delivering a
consistent and reliable development environment.

6
Chapter 1 Understanding the Laravel Ecosystem

Install Composer:
Installation for Linux, Unix, or macOS
Users using Linux, Unix, or macOS can install Composer by following the instructions in
the URL provided (https://getcomposer.org/doc/00-intro.md#installation-linux-
unix-macos).

Installation for Windows


For Windows users, the installation process is slightly different. Follow these steps to
install Composer:
Download and install Composer from the official website (https://getcomposer.
org/download/).
Verify the installation by running ‘composer --version’ in the command prompt. You
should see the Composer version displayed.

Install Laravel
Open a command prompt, navigate to the desired directory for your Laravel project, and
run the following command:

---------------------------------------------------------------------------
     composer create-project --prefer-dist laravel/laravel your-­
project-­name
---------------------------------------------------------------------------

Replace ‘your-project-name’ with the desired name for your Laravel project.
Composer will download and install Laravel and its dependencies.

Configure Environment Variables


Duplicate the ‘. env.example’ file in the root of your Laravel project and rename it to ‘.env’.
Update the ‘.env’ file with your database connection details and other configuration
settings, such as the application key.

7
Chapter 1 Understanding the Laravel Ecosystem

Generate an Application Key


The application key in Laravel is a random 32-character string that is used for different
security purposes such as encryption, hashing, and cookie signing. It is generated during
the initial setup of a Laravel application and must be kept secure.
Run the following command within your project directory to generate an
application key:

---------------------------------------------------------------------------
     php artisan key: generate
---------------------------------------------------------------------------

This command will produce a random key and store it in your Laravel project's .env
file, specifically in the APP_KEY variable. The key will resemble the following:

---------------------------------------------------------------------------
     bash base64 copy code:QqRchgn5/23n+js1FIoMBy3V9T2tYsa9vnruOHdr2Ns=
---------------------------------------------------------------------------

Keep the application key private and avoid distributing it publicly or storing it in
version control repositories. If you need to regenerate the key for whatever reason,
simply run the key:generate command again, and a new key will be generated and saved
in the .env file.

Run the Development Server


Start the Laravel development server by running the following command:

---------------------------------------------------------------------------
     php artisan serve
---------------------------------------------------------------------------

Access your Laravel application at ‘http://localhost:8000’ in your web browser.


Your Laravel development environment is now set up. You can start developing your
web application by creating routes, controllers, models, and views using the Laravel
framework.

8
Chapter 1 Understanding the Laravel Ecosystem

Key Concepts and Principles of Laravel


Laravel is built around several key concepts and principles that contribute to its
effectiveness and ease of use. Understanding these concepts is essential for working
efficiently with the framework. Let's explore these key concepts in brief.

Routing
Routing in Laravel refers to defining how incoming HTTP requests should be handled.
Routes define the URLs and map them to specific controller actions. For example, you
can define a route that maps the "/users" URL to a UserController's index action. Routes
provide a clean and expressive way to handle different HTTP methods (GET, POST, PUT,
and DELETE) and parameters.
For Illustration, refer to the following snippet:

---------------------------------------------------------------------------
Route::get('/users', 'UserController@index');
---------------------------------------------------------------------------

CRUD Routing
Let's now create CRUD (Create, Read, Update, Delete) routes for managing blog posts:

---------------------------------------------------------------------------
// routes/web.php
use App\Http\Controllers\BlogController;
// Show the list of blog posts
Route::get('/posts', [BlogController::class, 'index']);
// Show the form for creating a new blog post
Route::get('/posts/create', [BlogController::class, 'create']);
// Store a newly created blog post
Route::post('/posts', [BlogController::class, 'store']);
// Show a specific blog post
Route::get('/posts/{id}', [BlogController::class, 'show']);
// Show the form for editing a blog post
Route::get('/posts/{id}/edit', [BlogController::class, 'edit']);

9
Chapter 1 Understanding the Laravel Ecosystem

// Update a specific blog post


Route::put('/posts/{id}', [BlogController::class, 'update']);
// Delete a specific blog post
Route::delete('/posts/{id}', [BlogController::class, 'destroy']);
---------------------------------------------------------------------------

In the preceding example, we constructed routes for complete CRUD actions on blog
posts. These pathways correspond to the actions listed in the following:
index: This function displays a list of all blog posts.

create: Display a form for creating a new blog post.

store: Save the freshly created blog post to the database.

show: Display a certain blog post.

edit: Show a form for editing an existing blog entry.

update: In the database, update an existing blog post.

destroy: Removes a particular blog post from the database.

Controllers
Controllers in Laravel are responsible for handling user requests and managing the flow
of data in the application. Controllers contain methods, also known as actions, that are
invoked when a specific route is accessed. They receive user input, interact with models
and services, and return responses to the user. Controllers help separate the logic of an
application from the routing layer.
For Illustration, refer to the following snippet:

---------------------------------------------------------------------------
class UserController extends Controller {
    public function index() {
        $users = User::all();
        return view('users.index', ['users' => $users]);
    }
}
---------------------------------------------------------------------------

10
Other documents randomly have
different content
CHAPTER I

WATERLOO, THE MAYOR, AND THE BABY

The Fisherman—The Battle of Waterloo—The Mayor of


Salisbury—The Mayor’s Son—The Market-place—The Circus—
Boarding-School and Fun—A Diary.

One midsummer day in 1815 a young draper’s assistant was gently


fishing in the Salisbury Avon. William Fawcett was but lately come to
Salisbury, yet he already knew his river. While trying a deep pool in
the shadow of a bridge near the town he was startled by shouts
from the roadway above. ‘News from the army! A great victory!
Boney in flight!’
The fisherman forgot his fish, and hurried away to join the rejoicing
crowd gathering in the market-place. There having been bustled to
the roof of a stage-coach, and had the gazette containing the news
thrust into his hands, he read out in his remarkably clear and
resonant voice the account of the great battle of Waterloo.
Rejoicings. Seventeen years later, when the shopkeeper had
become the Mayor of Salisbury, he again led the town
in rejoicings. The great Reform Bill had become law. Salisbury
townsfolk were henceforth to have a voice in the councils of the
nation, and the barren hill on which stood the pocket borough of old
Sarum was no longer to mock them with its political power.
The town joyously prepared to celebrate the event. The houses were
decorated. Elaborate illuminations were set up. Victory, assisted by
Greek gods and goddesses, presided over a transparency in which
Britannia throttled the hydra of corruption, while Wellington and Peel
scowled in the background. Meat and beer were given to the poor;
in the market-place, at great fires lighted in the open air, whole
sheep were roasted. The smoke swirled blindly about the bustling
crowd, and then surged up past the latticed windows of the Mayor’s
house, to seek in ever thinning rifts the spire of the wonderful
cathedral that for centuries has watched over the destinies of the
town. The next day was held in the market-place a great banquet, at
which the Mayor presided; and after dinner all adjourned to the
Green Croft Cricket Ground, where his Worship led off the dance
with a prominent and elderly lady of the town—the Mayor
resplendent in plaited shirt frill and high stock, the buckles on his
shoes twinkling as he cut ‘pigeon wings,’ the lady sedate in her wide
brocade gown, her poke bonnet, and lace veil.
Fawcett’s heart was as light as his heels on that occasion. All his life
he had been a reformer, a staunch Liberal, ardent for the extension
of the franchise. It says much for his personal charm and worth that,
in a close Tory borough such as Salisbury then was, he should have
been chosen Mayor by his political opponents.
The Mayor So dear to his heart was the spirit of freedom that
and his Wife. the Mayor had forsooth to fall in love with the
daughter of the solicitor who acted as agent for the
Liberal party. Miss Mary Cooper was a good and clever woman,
deeply interested in politics, and as ardent a reformer as the man
she married.
The couple were sociable and humorous. They kept a good table,
laid in an excellent stock of wine, and diffused such a pleasant
atmosphere of hospitality that they became immensely popular, and
many distinguished people sought their company. But William
Fawcett was not only a good townsman, he was a good countryman
as well, a great jumper, a keen sportsman, a good shot, and a
renowned fisherman.
The Brick- In 1833, when the Princess Victoria was fourteen
house Baby. years old, when the negro slaves were being freed
throughout the British Colonies, when Stephenson
had completed his locomotive and the first railroads had been
started, when all things seemed to be pushing and striving for
independence and progress, in the Mayor’s old low red-brick house
overlooking the market-place, in a wonderful Elizabethan room, on
26th August, Henry Fawcett was born.
The baby seems to have been singularly like most other babies. He
shared the uneventful placidity of his nursery with an older brother,
William, and a sister, Sarah Maria. Six years later there came another
brother, Thomas Cooper.
The Market. When Harry was four years old Queen Victoria, whom
he was to serve in so distinguished a capacity, came
to the throne. But it was still too early to find in Harry indications of
the future statesman. He was delicate, and much spoiled at home,
had a strong will of his own, and was on the whole rather selfish. He
was not an imaginative child, though he loved at times, holding his
sister Maria tightly by the hand, to venture into the great cathedral
and see the coloured light as it filtered through the high windows, or
to thrill in response to the thundering of the great organ. But more
often we find him, still very tiny, standing squarely on his feet,
inquiring with real interest the price of bacon, how much sheep and
wool brought; or walking with his father and wearying him with
ceaseless economic questions as to ‘Why are things cheaper to-day
than last month?’ ‘Why does butter cost more than milk?’ until that
patient man was heard to exclaim not too patiently, ‘Harry asks me
so many questions that he quite worries me.’
HENRY FAWCETT’s MOTHER

He went to a Dame’s school, where his first teacher said that she
had never had so troublesome a pupil, that his head was like a
colander; but Harry puts the case more pathetically when he tells his
mother that ‘Mrs. Harris says if we go on, we shall kill her, and we
do go on,’ regretfully adding, ‘and yet she does not die.’ A
schoolmate of these days says that Harry lisped very much, and that
the boys used to tease him about it. He was also so slow about his
lessons that they called him thickhead. But when school was out
Harry entered the realms he loved. From his home on the market-
place he had only to go outside the door to be at once in touch with
the active world whose economic problems appealed to him so
keenly. He made friends among the country folk, and talked of their
crops and the money they would bring, and noted in his childish
mind the rise and fall in the price of wheat.
The Circus. Then to the same open space came all sorts of
travelling shows. Sometimes the circus spread its
mysterious tents, and when the children were dragged away from
the wild beasts and the seductive freaks and put to bed, the little
Fawcetts would stealthily creep to the bedroom window overlooking
the market and see the lights shining on all the wonderful but
forbidden marvels, and hear the hurdy-gurdy and the band mix their
triumphal blare with the solemn striking of the clock in the near-by
cathedral.
Boarding- In 1841 Harry’s father took a delightful farmhouse at
School. Longford, about three miles south of Salisbury, with
delectable streams full of fish. Harry loved to fish
every day, and hated lessons, but, alas! grim fate backed the
lessons, and sent him ruthlessly to school. He went as a boarder to
Mr. Sopp at Alderbury, a few miles away.
There are many tales showing that Harry loved the fleshpots and
that he had been much indulged at home. He writes, ‘I have begun
Ovid—I hate it.’ ‘This is a beastly school—milk and water, no milk—
bread and butter, no butter. Please give a quarter’s notice.’
And still more heartrending was the prayer to his mother, ‘Please
when the family has quite finished with the ham bone, send it to
me.’ Imagination can supply the effect of this on the family circle,
and guess what a well-covered ham bone was shipped to the
starving Harry. Starving or no, he grew immensely stronger and
larger, and though he never admitted that he got enough to eat at
any school, he became ultimately reconciled to his exile.
He used to come home often for half-holidays, and to go to Longford
and revel in all country delights. Then began the close friendships
with the cottagers about him which meant so much to him and
influenced all his life.
In the summer that completed his tenth year there came to
Salisbury two men who also loved the common people and sought to
make their lives easier. It was the year of the great Free Trade
campaign in the agricultural districts, and the men were Cobden and
Bright. They visited Harry’s father, and perhaps Harry himself met
them then for the first time. Lord Morley has said in his life of
Cobden that ‘the picture of these two men, leaving their homes and
their business, and going over the length and breadth of the land to
convert the nation, had about it something apostolic.’ In a home
where they and their teachings were so reverenced, to even hear of
their journeyings would make a strong impression on a boy of
Harry’s interests, and perhaps helped to give a definite aim to his
ambitions.
At Mr. Sopp’s school he began a diary, of which the penmanship is
admirable. On some days the only record is the startling fact, ‘It was
a very fine day.’ June 21st, 1847, however, is a very eventful day, for
he lists the capture of the first fish that he took with a fly, which
weighed ‘about three-quarters of a pound.’
Hedgehogs Again, he is transported with joy by the gift of a
and Cake. hedgehog and four young ones, and he has a
glorious time in going on board H.M.S. Howe, of one
hundred and twenty guns. On one occasion he goes to the theatre,
on another he is in court hearing a trial. He begins Greek, and this
anguish is modified by the arrival of a cake for one of his
schoolfellows, which Harry doubtless shares.
A change of scene is recorded in the diary when on 3rd August
Henry becomes the first pupil at Queenwood College. In its previous
career this temple of learning had been Harmony Hall, built by
Robert Owen for his last socialist experiment. In 1817 it was opened
as a school by Mr. Edmonson, a Quaker. Special emphasis was given
to scientific training and English literature. The school seems to have
been very congenial to Harry, and his intellect now began to develop
rapidly.
The Editor. To continue from the diary, we learn that ‘we elected
the various school officers. J. Mansergh and I were
elected without opposition editors of the Queenwood Chronicle.’ He
had been at Queenwood but a fortnight, and was fourteen years old
when this great honour came to him. Mr. Fawcett was delighted at
this good news, and offered because of it and because Harry had
been ’studying most determinedly’ to take the boy to Stonehenge.
His aversion to books had distressed his family, and this new interest
in his studies gave his father great pleasure. On reading a
composition which Harry had sent home, Mr. Fawcett exclaimed to
his wife, ‘I really think, mother, after all that there is something in
that boy!’ His literary performances at this time indicate an
increasing imagination, but in the main he never deviated from the
practical paths of thought shown when as a tiny child he studiously
investigated the Salisbury market. His schoolmates report him as ‘tall
for his age, loose-limbed, and rather ungainly.’ He had become much
of a bookworm, and though later good at games, at this time he
preferred to wander off by himself and read. He was strongest in
mathematics; languages did not much appeal to him; but he liked to
learn long passages of poetry by heart. There was a disused chalk-
pit near Queenwood where he would take refuge and declaim his
lines. The extravagance of his gesticulations might well cause
unexpecting passers-by to consider him the village loony.
CHAPTER II

THE BOY LECTURER

A Lecture on the uses of Steam—Parliamentary Ambitions—


King’s College—Politics in the Fifties—Cribbage and Cricket.

Fawcett was interested in the scientific lectures, and he had a very


good time. Professor Tyndall took them out surveying. Harry
comments on a lecture at which he heard that there ‘is fire in
everything, even ice’; he also records some chemical experiments in
the laboratory.
In September the diary states, ‘I began writing my lecture on
phonography, on the uses of steam without copying any of it.’
There is an error here, as these were two lectures, not one. That on
steam, in a blue marbled-covered copy-book, lies before the writer.
The title, inscribed in tall, shaded handwriting, contained within
scrupulously ruled lines, is:

=================================
A Lecture delivered by H. Fawcett
On Uses of Steam
At Queenwood College
September 27, 1847.
=================================
The ink, which was black sixty-six years ago, is now much faded; but
the essay of the fourteen-year-old schoolboy is still fresh and
interesting, and so prophetic of the man that it is like a simple map
indicating the chief features of the country we are about to see.
Henry writes in his careful penmanship, for which he must have
been marked at least 9+ in a scale of 10, ‘Things which appear
simple to an unobserving Person are to an observing Person the
most complicated and beautifully formed ... such a simple Thing as a
blade of Grass, has ever any Man been yet so wise as to tell what it
is?’
The Essayist. Here is another curious sentence written by the
bright-eyed youngster with the monumental dignity
of the lecturer:
‘What can be so beautifully contrived and framed as the human
Body, where there are innumerable Parts, acting all in Unity?... if one
of the Parts go wrong, the whole Body is put out of Tune ... is there
any one Part of our Body which we could dispense with?... I think
the Answer “No” must be evident to every one.’
It is curious that Fawcett should have been called upon later by the
loss of his eyesight to contradict this childish statement, and to
prove not only that we can get along without some of our most
precious faculties, but that the law of compensation so works that
we may be able to accomplish more by reason of the loss.
The essay proceeds to deal with railways, and contains all kinds of
figures relating to tonnage, trains, traffics, the cost of railroad
construction, etc., all with careful, correct figures; a complicated
study for a railroad expert. This schoolboy is already coping with the
figures and statistics of which he had later such a marvellous
control. He dwells on the importance of the railroad to the Wiltshire
farmer, who can sell his cheese at sevenpence a pound in London,
when it is only worth sixpence where it is made. In this and similar
statements we find the political economist foreshadowed: he speaks
of the nobility who selfishly object to having railways, which he feels
are the greatest help to the common people; and he adds, ‘A Man
should sacrifice a little of his own Pleasure when he knows that by
sacrificing that Pleasure he will benefit the People at large.’ We must
note that pleasure is always spelt with a beautiful and exceptionally
large P.
Later there are some intelligent remarks on the power of a railway to
create traffic, so that ’some Railways have been made between two
Places where there was not sufficient Traffic for a Coach, and yet
when they are made, a Trade springs up, and they pay very well
indeed.’
Transporta- He further approves of the railway as a means of
tion—Rich and cheap transportation, and remarks, ‘Many a Person
Poor. can avail himself of a Day’s Pleasure ...’ or, ‘Enjoy the
beautiful Air of some Country Village.’ Here we have not only the
keystone of Henry Fawcett’s character, but indications of the political
activities in which he was to be so pre-eminent. His public career
was one long, unbroken effort to do away with the monopolies and
prerogatives of any class, and so to increase the independence and
rights of the poor.
The essay continues by quoting from an article in the Quarterly
Review written in 1825, which considers it impossible that an engine
could travel eighteen miles an hour. With evident joy he quotes, ‘The
gross Exaggerations of the Powers of the Locomotive Steam Engine,
or to speak English, the Steam Carriage, may delude for a time, but
must end in Mortification to those concerned. We should as soon
expect the People of Woolwich to suffer themselves to be fired off in
Congreve’s Ricochet Rockets, as to trust themselves to the Mercies
of such a Machine going at such a rate.’ Harry himself then tells of
the M.P. who insisted that the best possible locomotive could not
compete with a canal boat. The scribe seems fully to appreciate the
humour of this, and so foreshadows the love of fun and the vibrant
laugh of the man to be.
Steam-engines lead to steamships. Our author now invites us to
cross ‘the wide heaving Ocean,’ saying, ‘When you are on a Voyage
in a Steam Vessel you feel none of that Inconvenience of having to
remain at Anchor for two or three Weeks waiting for a favourable
Wind ... you can proceed, for you are quite independent of the
Winds, and the Speed of a Steam Vessel is very considerably greater
than that of any other Vessel.’ A steam vessel went from Liverpool to
Boston in eleven days and nine hours, and yet when steam
navigation was struggling into existence ‘it struck the minds of our
brave Captains as a poor mean mechanical Thing unworthy of the
least Consideration.’... ‘I think you may almost remark’ (note the
conservative discretion) ‘that the greatest and most useful inventions
when they are struggling into Existence receive the greatest
Opposition, because they make great changes, and most people,
especially the ignorant, are generally very adverse to any changes.’
Patriotism— Now he boasts magnificently about the British navy
Bonaparte and and merchant marine, approves of Bonaparte’s
Babylon. wisdom in coveting the British sailors, and yet
prudently warns all against pride, citing the lamentable consequence
of lack of humility to Babylon and Nineveh. We are asked to consider
the relative values of coal, diamonds, gold, and silver, and are
informed that ‘every Difficulty can be overcome by steady
Perseverance—some Persons will never scarcely be overcome by
Difficulties—they say they will do it, and they will never rest till they
have performed what they want to, and it is to Men like these that
we are indebted.... No Improvements or Inventions will run into a
Person’s Mind like Water will run into a Bottle, but they come from
Years of Study and Perseverance.’
We are asked, ‘Do you suppose that Sir Isaac Newton established
the Laws of Gravitation without some trouble, do you suppose that
such a Piece of Poetry as Milton’s “Paradise Lost” was written
without a Moment’s Thought—or do you suppose that Watt improved
the Steam Engine without some hard Labour?’ Our scribe then
finishes his masterpiece with a stupendous finale, by the help of a
bit of poetry culled from an American newspaper and entitled the
’song of Steam,’ a verse of which will be sufficient:
‘I’ve no Muscle to weary, no Breast to decay,
No Bones to be laid on the “Shelf,”
And soon I intend you may go and play,
While I manage the World by myself.’

This magnum opus, being now successfully brought to completion, is


signed in full, no longer, as on the title-page, with only the initial of
his first name, but by Henry Fawcett, writ exceedingly large and
clear, Queenwood College, October 12th, 1847. Every page in the
marbled copy-book has been filled with various spellings, and only a
very few erasures, between 27th September and 12th October.
We have quoted this delicious essay as fully as space would allow,
not only on account of its unique charm, but because every page is
coloured by a preoccupation with those subjects and a love for those
traits of human nature which were later so characteristic of Henry
Fawcett, the teacher and statesman. In fact, we may accept this
essay on steam as his official debut. The lecture had an encore at
Salisbury in the family circle, when, as Harry writes, all were ‘much
pleased with it, and Papa promised to give me a sovereign for it.’
Phonography His lecture on phonography is much in the spirit of
and simplified to-day, when simplified spelling is causing such
Spelling. ardent controversies. Harry comments that ‘out of
fifty thousand Words in the language, only fifty are written as they
are pronounced.’ We must note that in these writings his own
inventions in spelling tend to change these statistics.
The range of his composition at this period is great. An article on
‘Angling and Sir Isaac Walton’ is in happy contrast to the account of
a first visit to London. Another fragment contains the acute
observation that ’statesmen depend upon their brains.’ In another
essay called ‘Reflection’ an imaginary trip is taken past Spain, during
which the author ponders on people who are ‘made poor by gold.’
Progressing to Egypt, we are told that Mahomet was ‘in many
respects a worthy man.’ Arriving in India, our guide tells us of a
company of men who, ‘occupying a house of no very considerable
size in London, have entirely from their enterprise and powers of
mind, got possession of many thousand acres of land.’ Does this
refer to the East India Company, and had Harry seen the stately East
India House in Leadenhall Street on that first visit to London?
The breathless exuberant feat of imagination and philosophy closes
with quotations from Portia’s lines to Mercy and Cicero’s oration on
Verres, both of which, the author truthfully says, ’show powers of
reflection.’
Harry was writing and studying with a definite end in view. Already
the youth had determined on a political career, and when the
schoolboys discussed their plans for the future he invariably declared
that he meant to be a Member of Parliament. The statement was
received with roars of laughter, but Harry remained imperturbably
sure.
Still at the He was at Queenwood for a year and a half, and then
foot of the went to London, where he first attended King’s
Class. College School, and then King’s College. A
schoolmate described him as ‘a very tall boy with pale whitey brown
hair, who always stood at the bottom of the lower sixth class.’
He attended the school in his fifteenth and sixteenth years, and then
went to lectures in the college until the summer of 1852, when he
was nineteen years old.
Standing in the school was, in those days, entirely determined by
knowledge of the classics, for which Fawcett showed a grand
indifference; but he gained the arithmetic prize in 1849, also the
class-work prize, the first prize in German, and the second in French
in the same term. His knowledge of these languages was always so
vague that we fear his teacher was over-partial in the award, or that
the other boys were strangely deficient. In 1850 he carried off
another honour for mathematics, and a first prize after that in the
Michaelmas term. The masters noted Fawcett’s unusual
mathematical power, and were also impressed by his ability to write
English prose.
King’s College At Easter in 1851 he left school and worked only at
and Cricket. the college for mathematics and classics. We hear
that he made no particular mark; but he occasionally
played billiards and cricket, and he was already an interested
spectator in the gallery of the House of Commons.
During his stay in London he lived with some family connections, a
Mr. and Mrs. Fearon. Mr. Fearon was a Chief Office Keeper at
Somerset House, and lived there. Somerset House adjoins King’s
College, and this was fortunate for Harry, who, when he first went to
London, had much outgrown his strength. The hours spent in the
little parlour tucked away in the vast building were not without
charm for the home-loving boy. Sitting on the corner of the horse-
hair sofa, with its relentless early Victorian back and its unyielding
springs, trying, mostly in vain, not to disturb Mrs. Fearon’s best
antimacassar, he would cheerfully play cribbage by the hour with his
hostess, while his host expounded pungently on the questions of the
day. Harry had passed from the Liberalism of the country home to
the Liberalism of the metropolis. For both, Bright and Cobden were
now leaders and standard-bearers, though Lord Palmerston was the
Party Chief. Free Trade had been won, but neither Parliament nor
country had settled down to it as a policy, and the need of another
and more democratic Reform Bill was looming up on the political
horizon.
These were the days that followed the abortive revolutions of ‘48.
The battle for political independence was raging everywhere, but
both leaders and rank and file were learning with bitterness to make
haste slowly. None the less, hearts were glowing hotly for Freedom,
and while Fawcett was in London, Kossuth, the Hungarian, was
welcomed with enthusiasm. He followed Carl Schurz, that valiant
apostle of Liberty, to America, where Garibaldi was already working
at his soap factory on Staten Island. There was no doubt as to the
heartiness of Kossuth’s reception across the Atlantic. The fire of
Freedom burnt to high heaven there: was it not sufficient proof of
this that the dandies of that land reverently encased their mighty
brains in the Kossuth hat? Talk of these great men, of their vain
endeavours, of the persecution of the poor, of the need of opening
cages and letting in the light of Freedom, made its mark on Harry,
and he often spoke afterwards of Fearon’s ‘quaint and forcible’
phrases.
In 1851 was the great Exhibition in Hyde Park. Did Harry’s tall head
peer above the crowd that lined the streets as Queen Victoria drove
in state to the opening of that proud achievement? One would like to
think that once with seeing eyes Fawcett beheld the little lady who
presided over England’s destinies throughout his working life.
And now Mr. Fawcett, senior, conscientiously counting his pennies,
and the ability which his son had already shown as a student, went
to his neighbour, the Dean of Salisbury. He showed the Dean Harry’s
mathematical papers, and asked for advice about the next step. It
was not customary for one of Harry’s social standing to go to a
university, and the strain on the paternal purse to send him there
would be considerable, but the Dean had no doubt that Cambridge
offered the proper opening. The sacrifice was cheerfully made.
CAMBRIDGE
‘I count life just a stuff to try the soul’s
strength on
—educe the man.’—Browning.
CHAPTER III

THE TALL STUDENT

Peterhouse—Quoits and Billiards—Trinity Hall—A Fellowship—


Lincoln’s Inn.

The new Harry knew that for his father’s sake it was necessary
Under- for him to be self-supporting as soon as possible, and
graduate. therefore chose his college on purely financial
grounds. He went to Peterhouse, where the fellowships could be
held by laymen, and were reported to be of unusual value.
His great friend, Sir Leslie Stephen, saw him there for the first time.
We cannot do better than quote from Sir Leslie’s biography of
Fawcett the impression his subject then made upon him:
‘I saw Fawcett for the first time a few months after his entrance (in
October 1852).... I could point to the precise spot on the bank of the
Cam where I noticed a very tall, gaunt figure swinging along with
huge strides upon the towing path. He was over 6 feet 3 inches in
height. His chest, I should say, was not very broad in proportion to
his height, but he was remarkably large of bone and massive of
limb.
‘The face was impressive, though not handsome. The skull was very
large; my own head vanished as into a cavern if I accidentally put on
his hat. The forehead was lofty, though rather retreating, and the
brow finely arched.
‘The complexion was rather dull, but more than one of his early
acquaintance speaks of the brightness of his eye and the keenness
of his glance. The eyes were full and capable of vivid expression,
though not, I think, brilliant in colour. The features were strong, and,
though not delicately carved, were far from heavy, and gave a
general impression of remarkable energy. The mouth long, thin-
lipped, and very flexible, had a characteristic nervous tremor as of
one eager to speak and voluble of discourse....
‘A certain wistfulness was a frequent shade of expression. But a
singularly hearty and cordial laugh constantly lighted up the whole
face with an expression of most genial and infectious good-humour.
[3-1]

3-1. Sir Leslie Stephen, speaking of the photograph reproduced to


face p. 26, says, ‘The rather peculiar expression of the eyes
results from the weakness of sight presently to be noticed
which made him shrink from any strong light.’
‘On my first glimpse of Fawcett, however, I was troubled by a
question of classification. I vaguely speculated as to whether he was
an undergraduate, or a young farmer, or possibly somebody
connected with horses at Newmarket, come over to see the sights.
He had a certain rustic air, in strong contrast to that of the young
Pendennises who might stroll along the bank to make a book upon
the next boat race.
HENRY FAWCETT BEFORE HE WAS BLIND

‘He rather resembled some of the athletic figures who may be seen
at the side of a north-country wrestling-ring. Indeed, I fancy that
Fawcett may have inherited from his father some of the
characteristics of the true long-legged, long-limbed Dandie Dinmont
type of north-countryman. The impression was, no doubt, fixed in
my mental camera because I was soon afterwards surprised by
seeing my supposed rustic dining in our College Hall. I insist upon
this because it may indicate Fawcett’s superficial characteristics on
his first appearance at Cambridge.
‘Many qualities, which all his friends came to recognise sooner or
later, were for the present rather latent, or, maybe, undeveloped.
The first glance revealed the stalwart, bucolic figure, with features
stamped by intelligence, but that kind of intelligence which we
should rather call shrewdness than by any higher name.’
Sports and At first the men of his own year were inclined to
Games. estimate Harry as an outsider in sports and games.
His simple provincial ways gave little sign of expert
skill. But he won his way in dramatic fashion. An undergraduate nick-
named the ‘Captain’ challenged him to a game of quoits. Salisbury’s
native game is quoits; Harry was well trained, and won easily. Then
the battle shifted to billiards. Captain’s score pushed steadily ahead
until in a game of a hundred points he had ninety-six to Harry’s
seventy-five: four points more for the Captain, twenty-five for Harry.
The onlookers vociferously offered ten to one on the Captain.
Fawcett gravely took all the bets offered at this rate, and any others
that he could get, and then calmly, in a single break, made the
twenty-five necessary points.
A successful Fawcett is quoted as having given this account, ‘Bets
Game of were forced on me; but the odds were really more
Billiards. than ten to one against my making twenty-five in any
position of the balls, but I saw a stroke which I knew that I could
make, and which would leave me a fine game.’ No matter by what
magic the feat was achieved, it filled his pockets, and cleared for
ever any doubts in his companions’ minds as to the capacity and
shrewdness of ‘Old Serpent,’ as he was then dubbed, and by which
nickname he went for a brief time.
He never gambled again. The story is paralleled in later years by an
equally solitary financial speculation. He then showed the same
quickness in seizing the facts and calculating the chances, the same
boldness in acting on his own judgment, and the same restraint in
not repeating the adventure.
He disapproved of gambling, and had a wholesome dislike of it. His
sense of fun made it impossible for him ever to have a holier-than-
thou attitude, but his common sense and natural goodness kept him
singularly free from the failings so common among his associates.
While anything but a Puritan, he ‘was in all senses perfectly
blameless in his life.’
Making He had a rare talent for friendship, attracting people
Friends. to him as easily as he was attracted to them, and his
faculty of making friends and keeping them held to
the end. He was never known to lose a friend.
Those who knew him well appreciated his strong intellectual
equipment. Perhaps his chief characteristics were his absolute
normality, his remarkable freedom from self-consciousness, his
common sense, and his ever-present sense of fun. These early years
at the university, when the lank boy was emerging into the
statesman, were years of great happiness and joviality. Fawcett
found many congenial spirits, and formed intimacies among men
destined to distinguished careers. Most of his associates were good
workers, but not particularly given to intellectual subtleties. Music
made slight appeal to him, and he was flagrantly ignorant of classics
and modern languages, and made no pretence to culture. The young
Cambridge men of this period were greatly afraid of sentimentality,
and devotees of the ‘God of Things as they are.’
But there was one subject peculiarly attractive to the men with
whom Fawcett consorted—political economy. And in those days
political economy meant Mill. His book, gathering together all the
last words of the science, had been written a very few years before
Fawcett went to Cambridge. It had had a phenomenal success, and
it and its author were enjoying a phenomenal authority. Edward
Wilson, a brilliant Senior, well represented the feeling of his day,
when he would confute all opposition by an apt quotation, leaving
Mill triumphantly supreme, and then close his vindication with the
cry, ‘Read Mill! Read Mill!’ Fawcett did, from early till late, until he
knew the book by heart. As he was thoroughly inoculated with this
cult, his reverence for Mill was one of his strong steadfast beliefs
through life.
Fawcett begrudged time taken from his books, and never rowed in
his college boat, although Sir Leslie Stephen writes:
Boating. ‘That he occasionally performed in the second boat, I
remember by this circumstance, that I can still hear
him proclaiming in stentorian tones and in good vernacular from an
attic window to a captain of the boat on the opposite side of the
quadrangle, and consequently to all bystanders below, that he had a
pain in his inside and must decline to row. I have some reason to
think that he had felt bad effects from some previous exertions, and
had been warned by a doctor against straining himself. I have an
impression that there was some weakness in the heart’s action.
Fawcett, like many men who enjoy unbroken health, was a little
nervous about any trifling symptoms. One day we found him lying in
bed, complaining lustily of his sufferings, and stating that he had
dispatched a messenger to bring him at once the first doctor
attainable. A doctor arrived, and his first question as to the nature of
Fawcett’s last dinner resolved the consultation into a general
explosion of laughter, in which the patient joined most heartily.’
It was characteristic of Fawcett that he treated all men as equals,
and took from them the best of what they had to offer. He became
intimate with men of all ages. Mr. Hopkins, a Peterhouse man, with
whom Fawcett read, had received his B.A. in 1827, twenty-five years
before Fawcett’s appearance at Cambridge; but this difference in age
did not prevent a close bond. Fawcett never alluded to Hopkins
without great enthusiasm, and in the days of his grave trial this
friend was the most helpful of all. He was of great service in the first
years at Cambridge, urging Fawcett to regard the mathematical
studies necessary for taking a good degree as valuable intellectual
gymnastics. Fawcett with his usual keenness and common sense was
quite alive to the fact that a good degree was a distinct commercial
Welcome to our website – the perfect destination for book lovers and
knowledge seekers. We believe that every book holds a new world,
offering opportunities for learning, discovery, and personal growth.
That’s why we are dedicated to bringing you a diverse collection of
books, ranging from classic literature and specialized publications to
self-development guides and children's books.

More than just a book-buying platform, we strive to be a bridge


connecting you with timeless cultural and intellectual values. With an
elegant, user-friendly interface and a smart search system, you can
quickly find the books that best suit your interests. Additionally,
our special promotions and home delivery services help you save time
and fully enjoy the joy of reading.

Join us on a journey of knowledge exploration, passion nurturing, and


personal growth every day!

ebookmasss.com

You might also like