Download as pdf or txt
Download as pdf or txt
You are on page 1of 70

Building Real-Time Marvels with

Laravel: Create Dynamic and Interactive


Web Applications 1st Edition Sivaraj
Selvaraj
Visit to download the full and correct content document:
https://ebookmass.com/product/building-real-time-marvels-with-laravel-create-dynami
c-and-interactive-web-applications-1st-edition-sivaraj-selvaraj/
More products digital (pdf, epub, mobi) instant
download maybe you interests ...

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 booktranslations@springernature.com; for reprint,
paperback, or audio rights, please e-mail bookpermissions@springernature.com.
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
Another random document with
no related content on Scribd:
liian hellämielinen, niin olisittehan voinut pyytää niitä, jotka ovat
voimakkaita, nujertamaan sellaisen mahtavan vihollisen?"

Ivan ei vastannut. Hän ei voinut sanoa mitään. Moite oli ansaittua,


mutta hänen tarkoituksensa oli ollut hyvä. Kohtalo oli ollut liian tyly.
Hän katseli nyt Mirkovitshia, kun julma nihilisti käveli edestakaisin
ahtaassa huoneessa ja hänen ankaroilla, karskilla kasvoillaan
kuvastui koston ajatuksia.

"Jospa vain tsaarin poika olisi vielä hallussani", hän mutisi, "niin
kaikki voitaisiin vielä pelastaa".

"Siis…?" kysyi Ivan jännittyneesti. "Dunajevski —?"

"On nyt turvassa Englannissa, ja tsaarin poika on palannut


Pietariin."

"En käsitä", sanoi Ivan ymmällään. "Kuinka siis asioista sovittiin?"

"Mahdollisimman yksinkertaisesti, naisen, tyttäreni, avulla", sanoi


Mirkovitsh.

"Maria Stefanovnan?"

"Näyttää siltä, että hänellä naisten tapaan oli joitakin epäilyksiä,


joista sivumennen sanoen monet tovereistamme olivat samaa
mieltä, oliko suotavaa, että vankimme surmattaisiin, kuten koko ajan
olin ehdottanut, jotta siten ylläpitäisimme terroria, jota emme voisi
aikaansaada diplomatian avulla. Kun teistä ei kuultu mitään ja tuntui
selvältä, että jokin onneton kohtalo oli tullut osaksenne, niin me
kaikki äänestimme kuolemantuomion puolesta.
"Hän keksi omasta päästään rohkean suunnitelman pakottaen
tuon vanhan hupsun Lavrovskin viemään uhkavaatimuksemme
tsaarille aivan samansisältöisenä kuin oli ollut kirje, jonka te itse
otitte viedäksenne Taranjeville. Kysymättä neuvoa komitealta hän
etsi miehen käsiinsä, sillä me olimme sitä ennen saaneet varmoja
tietoja, että hän oli pelkästä pelosta ollut jatkuvasti ilmoittamatta
mitään Pietarin hallitukselle. Kun tikari, niin sanoakseni, uhkasi
hänen herransa sydäntä, niin ei hänellä ollut muuta mahdollisuutta
kuin totella ja hänestä tuli kirjeemme kantaja. Emme tietenkään
tiedä, mitä tapahtui Pietarissa hänen ja korkeiden henkilöiden välillä,
mutta kolme päivää sitten viralliset sanomalehdet ilmoittivat vangitun
nihilistin Dunajevskin ja hänen toveriensa vapauttamisesta ja heidän
saattamisestaan rajan toiselle puolelle. Eräät komiteamme jäsenet
olivat heitä siellä vastassa mukanaan rahaa ja vaatteita, ja Maria
meni heidän kanssaan, sillä me kaikki olimme sitä mieltä, että olisi
parasta kaikille, jos hän asuisi Englannissa jonkin aikaa.

"Saman päivän iltana tsaarin poika vietiin silmät sidottuina


Heumarktilla olevasta talostani, ja siten päättyi ovelin salajuoni, mitä
mainio veljeskuntamme milloinkaan en kyennyt keksimään."

"Kiittäkäämme Jumalaa siitä", sanoi Ivan lämpimästi.

"Kirotkoon Jumala sinua pannessasi meidät kaikki vaaralle alttiiksi


heti kunniakkaan voittomme jälkeen", tokaisi Mirkovitsh raa'asti, "ja
kirotkoon hulluutemme, että olemme niin suuresti sinuun luottaneet".

Nuori puolalainen ponnahti pystyyn herjauksen kuullessaan.

"Luottamustanne ei ole petetty, Mirkovitsh", hän sanoi tyynesti,


"eivätkä toverimme eikä asiamme ole vaarassa. Antakaa minulle
tarpeelliset rahat ja oikeuttakaa minut käyttämään niitä, ja vannon
teille, että kolmen päivän kuluttua luovutan paperimme varmasti
teidän haltuunne, jotta te sen jälkeen saatte toimia niiden sekä
minun kanssani, niinkuin itse haluatte."

"Tiedätte siis, missä kynttilänjalat tällä hetkellä ovat?" sanoi


Mirkovitsh hieman rauhoittuneena.

"Ne myydään huutokaupalla ensi torstaina, ja me voimme ostaa


ne sangen helposti."

"Niin! Ellei kohtalo tai madame Demidov tule väliin."

"Madame Demidov ei voi tietää, missä kynttilänjalat ovat.


Grünebaum vangittiin puoli tuntia sen jälkeen kuin näin hänet.
Ei ole todennäköistä, että hän olisi kavaltanut Lontoossa olevaa
rikostoveriaan, ja hän ei siis ole voinut päästä niiden jäljille."

"Teidän pitää toimia, niinkuin parhaaksi näette, Ivan", sanoi


Mirkovitsh vihdoin, "sillä tiedätte, että meillä on runsaita varoja, jotka
kuuluvat veljeskunnalle, ja Lobkowitz on asettanut ne
käytettäväksenne. Meidän täytyy teihin vielä toistaiseksi luottaa —"

Ja hän lisäsi lyhyen tauon jälkeen:

"Sen jälkeen henkenne on meidän vallassamme."

Sen Ivan tiesi aivan hyvin. Hän tiesi, että jos tämän jälkeen
veljeskunnalle koituisi joitakin ikävyyksiä, hänen ei annettaisi kärsiä
eikä kuolla heidän kanssaan. Hän tiesi, että hänet merkittäisiin
petturin polttomerkillä, että hänet hyljättäisiin, häntä herjattaisiin, ja
hän kuolisi yksinään salaperäisesti kostajan tikarin pistosta, eikä
hänelle suotaisi marttyyrien tavallista kuolemaa.
Mirkovitsh ojensi hänelle maksumääräykset ja rahat, jotka
Lobkowitz oli hänelle antanut. Siinä oli iso summa, ja Ivan otti sen
vastaan tuntien mielensä keventyneen. Vanha venäläinen lähti pian
hänen luotaan, ja Volenski sai olla rauhassa ja suunnitella
mielessään asiat. Keskustelu Mirkowitshin kanssa oli ollut kovin
myrskyinen, ja tarvittiin voimakkaita tahdonponnistuksia voimien
kokoomiseksi viimeiseen suureen yritykseen, jotta hän ja hänen
toverinsa pelastuisivat hirveästä perikadosta.

Ilmeisesti oli ensin saatava pääsykortti Curzon Streetin huoneiston


katselemiseen, jotta saisi selville, että keisarin kynttilänjalat olivat
myytävien tavarain joukossa. Kun hän olisi saanut varmuuden siitä
tärkeästä seikasta, niin olisi hänen viimeisenä toimenaan mennä
torstaina huutokauppaan ja käytettävikseen uskottujen varain avulla
tehdä tarjouksia keisarin kynttilänjaloista, kunnes ne tulisivat hänen
omikseen.

Hänen ohjelmansa ensimmäinen osa oli hyvin helppo toimittaa.


Seuraavana aamuna hän sai kortin Gideon, Eyre & Blackwellin
toimistosta ja sai tietää, että nuo hänelle kohtalokkaat kynttilänjalat
olivat niiden tavarain joukossa, jotka myytäisiin seuraavana päivänä.
Siis kaikki oli toistaiseksi hyvin.

Oli paljon ihmisiä tarkastamassa huonekaluja ja taiteellisia


koruesineitä, joita siellä oli monia tuhansia, mutta ne olivat
enimmäkseen juutalaisia — luultavasti kauppiaita, ja Volenski tiesi,
että summa, jonka salaseura oli asettanut hänen käytettäväkseen,
olisi paljon isompi, kuin mitä rikkainkaan kauppias maksaisi yhdestä
ainoasta koruesineestä. Hän oli siis aivan tyytyväinen seuraavan
päivän huutokauppaan nähden. Kun hän poistui talosta, niin hän
pysähtyi porraskäytävään sytyttääkseen sikarin. Samassa hetkessä
pysähtyivät talon edustalle myöskin eräät vaunut. Nainen astui niistä
ulos kädessään pääsykortti, ja huomaamatta Volenskia hän livahti
hänen ohitseen ja meni taloon. Se oli madame Demidov!

Volenskin mieleen ei todellakaan milloinkaan ollut juolahtanut, että


madame Demidov tai kardinaali voisi millään tavalla saada tietää
kadonneiden kynttilänjalkojen olinpaikasta, ja kun hän huomasi
naisen olevan paikalla, niin se vaikutti häneen kuin salamanisku.
Mutta sehän olikin oikeastaan aivan luonnollista. Kaksi viikkoa oli
kulunut varkaudesta. Grünebaumin oli sillä välin, kuten Volenski
hyvin tiesi, hänen rikostoverinsa ilmiantanut. Hänen talonsa ja
kirjansa oli tarkastettu, hänen lontoolaisen rikostoverinsa nimi oli
saatu selville, ja madame Demidov oli epäilemättä toiminut aivan
samalla tavalla kuin Volenskikin. Ja hän oli joko uhkailemalla tai
lahjomalla seurannut varastettujen kynttilänjalkojen jälkiä Daviesin
liikkeestä mr James Hudsonin taloon.

Volenski käsitti heti, että hänen läsnäolonsa olisi mitä haitallisinta


hänelle. Nyt oli aivan ilmeistä, että hän jonkin salaisen
henkilökohtaisen harrastuksen takia tahtoi saada kynttilänjalat
takaisin, sillä muuten hän ei olisi itse tullut Lontooseen, vaan olisi
lähettänyt taitavan asiamiehen valtaamaan varastettuja tavaroita.

Jos hän aikoisi huutaa niitä seuraavana päivänä, niin Volenski


tiesi, että se koituisi hänen turmiokseen. Hän voisi itse kyllä panna
menemään sangen huomattavan rahasumman tällaisen
välttämättömän tarpeen sattuessa, mutta mikäli huhut olivat oikeita
ja madame Demidov oli Venäjän hallituksen palkattu agentti, niin
silloin hänen luottonsa olisi todella rajaton ja taistelu heidän välillään
kävisi elämästä ja kuolemasta.
Oh! Kunpa voisi saada selville, mitä vuorokautta myöhemmin tulisi
tapahtumaan, ja saisi tietää heti kaikki uhkaavat onnettomuudet!
Kerran hän ajatteli jo tiedustella Lontoon joka hotellista madame
Demidovia, jotta saisi kuulla kohtalonsa hänen omilta huuliltaan,
mutta huomioonottamatta sellaisen toimenpiteen toivottomuutta niin
isossa kaupungissa kuin Lontoossa hän ajatteli, että nainen pitäisi
sitä heikkouden osoituksena, ja loppujen lopuksi, niin toivorikas on
ihminen, oli vielä pieni mahdollisuus, ettei madame Demidov vielä
ollut löytänyt salaisia papereita. Siinä tapauksessa hän, kun hän
tuntisi Volenskin huutajien joukosta, luopuisi kilpailusta luottaen
siihen, että hän toimi kardinaali d'Orsayn puolesta. Ei, kaikki ei vielä
ollut menetetty, ja Volenskilta pääsi syvä helpotuksen huokaus, kun
hän ajatteli, että huomenna joka tapauksessa — onnellisesti tai
onnettomasti — päättyisi tämä kauhea jännitys, jota hän oli saanut
kärsiä kaksi kuolettavaa viikkoa, lukuunottamatta muutamia autuaan
tiedottomuuden päiviä.

Mutta mitä oli tehnyt madame Demidov? Hän, kuten Volenskikin,


oli kärsinyt vaihtelevia epävarmuuden, pelon, epäilysten ja toivon
tuskia viimeisten kolmen viikon aikana. Heti Grünebaumin
vangitsemisen jälkeen hän oli saanut ilmoituksen poliisilta, mutta
kauhukseen hän ei ollut löytänyt kynttilänjalkoja juutalaisen liikkeestä
takavarikoitujen tavarain joukosta. Hänen onnistui töin tuskin ja vain
tuhlaamalla ison joukon venäläistä rahaa saada kahdenkeskinen
keskustelu vangin kanssa, joka himoitsi kovasti kostoa ajatellessaan
Volenskin luuloteltua petosta ja hyvin mielellään ilmoitti hänelle kaikki
tietonsa kynttilänjalkojen olinpaikasta.

Tarvittiin aika paljon enemmän venäläisiä rahoja, jotta saatiin Isaac


Davies puhumaan kynttilänjaloista jälleen. Hän oli epäluuloinen eikä
pitänyt salaperäisyydestä, joka punoutui niiden ympärille. Hän kielsi
kauan jyrkästi tietävänsä mitään niistä, ja vain runsaasti lahjomalla
saatiin hänet ilmoittamaan asiakkaan, jolle hän oli myynyt
kynttilänjalat.

Madame Demidov meni kuten Volenskikin mr James Hudsonin


taloon luottaen usein koeteltuun viehätystaitoonsa saadakseen
miehen luopumaan kirjeestä, jota hän kuvaili itselleen vaaralliseksi.
Ja kuten Volenskikin hän tunsi itsensä sanomattoman epätoivoiseksi
saadessaan kuulla, että mr Hudson oli kuollut.

Viikkoa myöhemmin, kun madame Demidov oli nähnyt ilmoituksen


Timesissä, ja kokonaan aavistamatta, että Volenski liikkui samoilla
asioilla kuin hänkin, hän tunsi itsensä sangen tyytyväiseksi
nähdessään, että kynttilänjalat olivat myytäviksi aiottujen tavarain
joukossa Curzon Streetin n:ossa 108. Hänen olisi ihmeen helppoa
huutaa niitä ja ostaa ne millä hinnalla tahansa.
XX

Paljon ihmisiä oli jo kokoontunut ruokasaliin, missä huutokauppa oli


pidettävä, kun Volenski saapui näyttämölle.

Monet kauppiaat, joista useimmat olivat juutalaisia, jotka kaikki


näyttivät tuntevan toisensa, järjestäytyivät rauhallisesti ostaakseen
kukin oman osansa. Myynti alkoi täsmälleen kello yhdeltätoista.
Volenski katsoi tuskallisesti ympärilleen — huone oli tiukassa väkeä.
Hän ei voinut nähdä madame Demidovia. Ensin huutokaupattiin
isommat huonekalut vaihtelevilla hinnoilla eri kauppiaille, joista
useimmat saivat ostoksensa hyvin halvalla. Ainoan kerran nousivat
hinnat hieman korkeammalle, kun eräs onneton ulkopuolinen tai
yksityinen huutaja yritti kilpailla kauppiasjoukkueen kanssa, joka oli
kasautunut lähelle huutokaupanpitäjän pöytää ja nopeasti nosti
hintoja, kunnes onneton yksityinen tarjooja vetäytyi syrjään
pettyneenä ja alakuloisena.

Vasta myöhään päivällä oli kuriositeettien ja arvokkaan rihkaman


vuoro tulla huutokaupattavaksi. Jalokiviä, kultaista ja hopeista
pöytäkalustoa, egyptiläisiä ja muita antiikkitavaroita ja vihdoin:
"Pari harvinaista kultaista ja posliinista kynttilänjalkaa", huusi
huutokaupanpitäjä, "sanokaamme viisikymmentä puntaa parilta".

"Viisikymmentä guineaa", sanoi eräs ääni.

"Kuusikymmentä", sanoi toinen.

"Seitsemänkymmentä", "kahdeksankymmentä",
"kahdeksankymmentäviisi", jatkoivat nopeasti eri kauppiaat.

Tähän alkuotteluun Volenski ei ollut puuttunut. Hän odotti, kunnes


useimmat huutajat olivat luopuneet pelistä, sillä hän tiesi hyvin, että
edeltäpäin oli järjestetty, kenen piti tarjota kynttilänjaloista
viimeiseksi.

Mutta kun taas ääni oli sanonut: "yhdeksänkymmentä", syntyi


hiljaisuus ja huutokaupanpitäjä alkoi tapansa mukaan:

"Siis, hyvät herrat. Pari harvinaista —"

"Sata", sanoi Volenski äänellä, jota hän tuskin tunsi omakseen,


niin kiihtynyt hän oli.

"Ja viisikymmentä", kuului edestä nenä-äänellä.

"Kaksisataa", sanoi Volenski.

"Ja viisikymmentä", sanoi nenä-ääni.

"Kolmesataa", sanoi Volenski, joka tunnettuaan vastustajansa


erääksi kauppiaaksi, joka oli ostanut ison kokoelman muita tavaroita,
tiesi, että vaikka hän pakottaisikin hänen tarjoomaan aika
huomattavan summan, niin hän ei kuitenkaan ostaisi koruesineitä
hinnalla, joka tuottaisi hänelle tappiota. Hän sai siis täydellisesti
malttinsa takaisin, ja hänen kova jännityksensä oli hiukan
lieventynyt. Ja kun nenä-ääni sanoi taas: "ja viisikymmentä", niin
Volenski sanoi rauhallisesti:

"Viisisataa puntaa."

Silloin nenä-äänen omistaja kohautti olkapäitään ja katsoi kattoon,


ikäänkuin hän olisi toivonut saavansa sieltä jonkin merkin,
minkälaista hänen seuraava menettelynsä tulisi olemaan. Hän mutisi
vielä: "ja viisikymmentä", mutta ilman vakaumusta. Ja kun Volenski
sanoi "kuusisataa", niin nenä-ääntä ei enää kuulunut.

"Siis, hyvät herrat", sanoi huutokaupanpitäjä, "tämä harvinainen


kynttilänjalkapari menee kuudensadan punnan hinnasta —
kuusisataa puntaa on tarjottu — hyvät herrat —"

"Seitsemänsataa", kuului soinnukas naisen ääni.

Kaikki kääntyivät katsomaan siihen suuntaan, mistä ääni oli


kuulunut, ja uteliaat silmät tarkastelivat uutta huutajaa. Volenski ei
kääntynyt ympäri. Hän tiesi hyvin, kenen ääni se oli — tuo pehmeä
ääni, jossa oli hiukkanen venäläistä sävyä konsonanttien
lausumisessa. Hän oli tullut kuolon kalpeaksi. Hänen kielensä tuntui
tarttuvan kiinni hänen kitalakeensa. Hänen polvensa alkoivat horjua
hänen allaan. Mutta sekunnin ajalla kaikki tämä pelko oli loppunut.
Hän ponnistautui äkkiä tarmokkaaksi ja ojentautui supisuoraksi ja
melkein uhmaavalla äänellä hän huusi huutokaupanpitäjälle: "Tuhat
puntaa".

"Ja viisisataa", kuulutti yhtä uhmaavalla äänellä hänen kaunis


vastustajansa heti.
"Kaksituhatta", sanoi Volenski.

"Ja viisisataa", kuului vastaus. "Kolmetuhatta, neljä-, viisi-,


kuusituhatta puntaa."

Ihmiset kuuntelivat jännittyneinä ja hengitystään pidättäen ja


vuoron perään katsoivat molempia tarjoojia, jotka huoneen
vastakkaisista päistä käheällä ja kuumeisella äänellä huusivat
uhmaten toisiaan. Kaikki huomasivat, että oli kysymyksessä jokin
salaperäinen asia, jokin murhenäytelmä, jonka viimeistä näytöstä
näyteltiin heidän silmiensä edessä.

Asioiden ollessa sillä asteella huutokaupanpitäjä kumartui


eteenpäin ja kääntyen erikoisesti Volenskin puoleen sanoi:

"Ellei jollakin tavalla saada sopimusta aikaan, niin en voi pitää


näitä herroja odottamassa. Meidän täytyy jatkaa myyntiä."

"Hyväksyttekö tarjoukseni?" sanoi Volenski. "Minä sanoin


kymmenentuhatta puntaa."

"Kaksikymmentätuhatta", sanoi madame Demidov tyynesti,


ikäänkuin hän olisi puhunut yhtä monesta pennistä.

"Kaksikymmentätuhatta puntaa", sanoi huutokaupanpitäjä,


"kynttilänjalkaparista. Sekä tämä herrasmies että tämä nainen ovat
aivan tuntemattomia minulle. Minun pitää saada jokin takuu
molemmilta, että rahat maksetaan, kun tarjous on hyväksytty,
muussa tapauksessa minun pitää kieltäytyä kuluttamasta enää
näiden herrasmiesten kallista aikaa. Olen sitä mieltä, että on tehtävä
jokin sopimus. Toistaiseksi viimeinen kahdenkymmenentuhannen
punnan tarjous pitää paikkansa."
Volenski oli vastaamaisillaan kiukkuisesti ja terävästi, sillä hän
kiehui tukahdutetusta kiihtymyksestä, kun hän tunsi käsivarteensa
kevyesti koskettavan. Hän kääntyi kuin umpikujaan ajettu eläin ja
katsoi silmästä silmään vihollista, joka todellakaan tällä hetkellä ei
näyttänyt niinkään hirvittävältä. Vihollinen oli sievästi puettu —
pelkkään mustaan. Hänellä oli tummat silmät, jotka katsoivat melkein
rukoillen Volenskin hurjistuneihin silmiin, ikäänkuin ne olisivat
tahtoneet lukea, mitä tapahtui hänen ajatuksissaan, ja hänellä oli
ääni, jossa oli vienoin venäläinen korostus, mitä hän milloinkaan oli
kuullut. Lisäksi oli hänellä pieni hienon käsineen verhoama käsi, joka
lepäsi kuin arka lintu Volenskin takin hihalla. Lopulta vihollinen puhui:

"Herra", sanoi hän venäjäksi, "tuntuu siltä, että taistelemme


peloittavan julmaa taistelua, te ja minä. Ehdotan muutaman hetken
aselepoa. Hyväksyttekö valkoista lippua?"

Volenski nyökkäsi heikosti myöntyvänsä.

"Herra, te ja minä näytämme sydämemme pohjasta -tahtovan


omistaa nuo kynttilänjalat. Ihmettelen, onko teidän tarkoituksenne
yhtä puhdas kuin minun? Nuo kynttilänjalat, hyvä herra, uskoi
huostaani eräs ystävä. Ne katosivat, kun ne olivat minun hallussani.
Tahdon palauttaa ne itse hänelle, vaikka se maksaisi puolet
omaisuuttani."

"Madame", sanoi Volenski, "kunnioitan vaikutteitanne, mutta nämä


kynttilänjalat uskoi hänen majesteettinsa keisari itse isännälleni
kardinaalille. Ne tullaan palauttamaan hänen ylhäisyydelleen, mutta
minun kätteni kautta."

"Ah!" sanoi madame Demidov ivallisesti, "tahdotte vaatia


palkkiota".
"Niin, madame, se on aikomukseni."

"Qu'à cela ne tienne! [Älköön se olko esteenä.] Lupaan teille yhtä


rajattoman palkkion kuin antelias kardinaali vain voi kuvitella, jos
suostutte oikkuuni."

"Madame, vaikka pitäisitte pienessä kädessänne Persian shaahin


yksityiskassaa, en antaisi kynttilänjalkoja teille."

"Kolmekymmentätuhatta puntaa tuosta kynttilänjalkaparista", hän


huusi huutokaupanpitäjälle, joka joukon mukana tarkasteli
vihamiehiä, joka joukko omituisesti höristi korviaan saadakseen
selvää keskustelun sisällyksestä.

"Herra", sanoi madame Demidov kiihtyneesti, "emmekö voisi jakaa


noita kynttilänjalkoja? Täytyykö teidän saada molemmat?"

Tämä ehdotus oli niin erikoinen, että Volenski ei ollut tajuta sen
täyttä merkitystä. Hän katsoi melkein häikäistynä kauniiseen
venakkoon, joka jatkoi kiihkeästi.

"Herra, kynttilänjalkoja on kaksi kappaletta. Toinen on hieman


vahingoittunut, toinen aivan eheä. Annan teille edellisen, jos saan
jälkimmäisen. Siten jaamme kunnian ja maineen lahjoittaessamme
takaisinsaadut aarteet hänen ylhäisyydelleen. Otaksun, että minä
naisena saan vahingoittumattoman ja sentähden paremman
kappaleen?"

Mitä hän sanoikaan? Vahingoittumattoman kynttilänjalan? Ja hän


saisi vioittuneen. Sehän oli se, missä paperit olivat, ja hän tahtoi
toisen. Mutta silloinhan hän oli pelastettu! Pelastettu! Hän ei voinut
puhua, hän oli liian kiihtynyt. Mutta ottaen madame Demidovia
kädestä hän veti hänet joukon halki, joka teki heille tietä,
huutokaupanpitäjän pöydän luo, missä kynttilänjalat olivat näytteillä.
Hän sanoi:

"Kyllä, kyllä, minä suostun. Te saatte toisen, paremman. Antakaa


minulle vioittunut, niin olen tyytyväinen. Miksi ette ota sitä? Minä
maksan niistä molemmista", hän lisäsi kuumeisesti ottaen ison
pinkan setelirahoja lompakostaan ja tyrkkäsi ne hämmästyneen
huutokaupanpitäjän käteen.

Mutta madame Demidov oli vain kerran vilkaissut


kaksoiskynttilänjalkoihin, sitten hän peräytyi ja hänen silmänsä olivat
melkein irtautumaisillaan päästä kauhusta ja pelosta. Kynttilänjalat
olivat todellakin kaksosia, sillä niissä monenlaisissa vaiheissa, joiden
alaisia ne olivat olleet viimeisten viikkojen aikana, oli
vahingoittumattoman Amorin käsi niinkuin sen toverinkin särkynyt
ranteesta kyynärpäähän asti.

Madame Demidov, joka turhaan koetti tekeytyä tyyneksi, sieppasi


kuumeisesti toisen kynttilänjalan hurjasti toivoen, että onni suosisi
häntä valinnassaan, ja hän lähti huoneesta katselijain
kummastuneen tuijotuksen seuraamana, jotka katselijat
vaistomaisesti tekivät tietä salliakseen hänen kulkea ohi
kallisarvoisen taakkansa kerällä.

Volenski, joka ei ollut huomannut naisen kauhistunutta ilmettä eikä


todennut sen syytä, näki vain luulemansa oman kynttilänjalkansa,
joka sisälsi hänen salaiset paperinsa. Tuskin luottaen aisteihinsa,
pelon ja toivon tunteiden vaihdellessa, hän otti sen mukaansa.
XXI

"Monsieur, — Luullakseni tämä kirje ei tuota teille mitään yllätystä.


Olemme toistemme vallassa. Todennäköisesti ei meitä
kumpaakaan hyödyttäisi tämän taistelun loppuun asti käyminen.
Emmekö voisi vaihtaa todistuskappaleitamme tänä iltana
hotellissani — nautittuamme saksanpähkinöitä ja viiniä? Syön klo
7.30. — Teidän

Anna Demidov."

Ivan Volenski piti kädessään hienotuoksuista, vaaleanpunaista


pientä kirjettä ja luki lukemistaan sitä, kunnes hän osasi sen ulkoa.
Hänen kauhea seikkailujensa sarja, joka oli kestänyt kaksi viikkoa,
loppui niin omituisella tavalla, ja sen huippupisteenä oli raju taistelu
huutokaupanpitäjän pöydän edustalla, ja Ivan, joka ei ollut vielä
kolmenkymmenen vuodenkaan vanha ja oli mies, ennenkuin
hänestä tuli sosialisti, ajatteli vihollista, jonka hän oli tuntenut ja jota
hän oli pelännyt jo niin kauan, kun tämä seisoi rukoilevasti hänen
vieressään, samalla kuin hänen pieni hansikoitu kätensä lepäsi
hänen takkinsa hihalla.
Siitä hetkestä asti hän näytti muistavan jokaisen sitä seuraavan
tapahtuman ikäänkuin epäselvänä unena. Hän oli kahmaissut
mukaansa kynttilänjalan, jossa hän luuli olevan salaiset paperit,
tuntien hurjaa riemua, ja hän oli vienyt sen hotelliinsa. Kun sitten
hänen huoneensa ovi oli taatusti lukossa, hän oli painanut salaista
jousta ja nähnyt paperien olevan kätköpaikan syvyyksissä. Vapisevin
käsin hän oli ottanut ne ulos ja hänen kivistävät silmänsä olivat
tarkastelleet niitä kuumeisesti.

Oh! Hän tunsi kuvaamatonta kauhua, kun hän totesi, että


kirjoitukset ja paperit eivät olleet niitä, joiden puolesta hän oli niin
urhoollisesti taistellut, katkerasti ponnistellen. Hänet valtasi
epätoivon lohduton tunne, joka herpaisi hänen sielunvoimansa ja
turrutti ne siinä määrin, ettei hän tajunnut, mitä papereita hän piti
kädessään.

Tuskin puolta tuntia myöhemmin hän kuuli Mirkovitshin raskaita


askeleita portaista, ja silloin hänen onnistui karistaa
tunteettomuutensa.

Vanha sosialisti oli koettanut Ivanin ovea, mutta huomatessaan


sen lukituksi oli ilmeisesti mennyt pois jälleen. Ivan ei silloin tahtonut
tavata häntä. Hän alkoi ajatella, ja ajatella hänen täytyikin rauhassa
pelkäämättä ja täydellisesti häiritsemättä.

Madame Demidov, Venäjän hallituksen agentti, oli saanut


haltuunsa sosialistisen veljeskunnan paperit. Se oli totta, mutta sen
sijaan Volenskilla oli hallussaan papereita, jotka koko maailman
silmissä leimaisivat madamen Venäjän poliisin vakoojaksi ja ikuisiksi
ajoiksi estäisivät häntä enää harjoittamasta sitä ammattia. Jos tulisi
yleiseen tietoisuuteen, että hänen paperinsa olivat joutuneet vääriin
käsiin, niin hänen hallituksensa, kuten on tavallista sellaisissa
tapauksissa, olisi tunnustamatta häntä agentikseen ja mahdollisesti
kostaisi hänelle hänen huolimattomuutensa takia.

Oli siis selvää, että vaikka veljeskunta oli tällä hetkellä madame
Demidovin vallassa, oli kaunis venakko samoin veljeskunnan
vallassa.

Ivan oli tyynesti ajatellessaan päässyt tähän tulokseen, kun


tarjoilija oli tuonut hänelle vaaleanpunaisen, hyvältätuoksuvan
kirjeen, joka oli jätetty hotelliin herra Volenskille annettavaksi,
samalla kuin kirjeen kantaja odotti vastausta.

Se oli riemuhetki Volenskille. Nainen oli kirjoittanut järkevästi.


Kumpaakaan heistä ei hyödyttäisi niin tasaväkisen taistelun loppuun
asti taisteleminen.

"Madame. Tänä iltana klo 7.30 tulen luoksenne, kuten


armollisesti olette pyytänyt minua, ja luotan siihen, että
vihollisuutemme, kun yhteisesti olemme riisuutuneet aseista,
vaihtuu ystävyyteen saksanpähkinäin ja viinin ääressä.

Teidän nöyrä ja harras palvelijanne

Ivan Volenski."

Hän lähetti tämän kirjelapun alas ja pukeutui nopeasti välttäen yhä


tarkoituksellisesti juroa toveriaan, jota hän ei tahtonut tavata,
ennenkuin hän voisi luovuttaa kohtalokkaat paperit hänelle.
XXII

Ja sinä iltana eräässä Claridge-hotellin sievästi kalustetussa


arkihuoneessa mies ja nainen istuivat iloisesti liekehtivän tulen
ääressä pohtien äskeisiä yhteisiä seikkailujaan ajaessaan takaa
keisarin kynttilänjalkoja. He olivat molemmat luovuttaneet toisilleen
toistensa vaaralliset paperit, ja kun se oli tapahtunut, niin
kummaltakin pääsi helpotuksen huokaus, ja siro valkoinen käsi
ojentui ystävyyden ja yhteisen vaitiolotakauksen merkiksi.

Ja kirjan tekijälle on kerrottu, hyvin arvovaltaiselta taholta, että


tämä sopimus on hyvin uskollisesti pidetty, sillä Lobkowitz ja
Mirkovitsh eivät milloinkaan enää ole voineet taivuttaa Volenskia
liittymään heidän loputtomiin vehkeisiinsä ja salajuoniinsa. Hänen
palautettuaan paperit julman vanhan Mirkovitshin haltuun pyysi
veljeskunta häneltä turhaan uusia palveluksia, eikä hän milloinkaan
enää tullut takaportaista heidän kokouksiinsa synkkään Wienin
taloon. Ja Venäjän hallituksen täytyi pian hyväksyä madame
Demidovin erohakemus, koska hän menisi kohta naimisiin.

Eräänä talvena, loistavissa prinsessa Marionovin pitämissä


tanssiaisissa palatsissaan Pietarissa, rouva Volenski, o.s. Demidov
oli varmaankin kaikista kaunottarista ihailluin.
Ei kukaan kuitenkaan huomannut, että hän ja hänen miehensä
vaihtoivat merkitsevän hymyn, kun prinsessa näytti vierailleen pari
harvinaista vieux Vienne-kynttilänjalkaa, joista hiljaa kuiskailtiin, että
hänen ylhäisyytensä paavin lähettiläs itse oli ne hänelle lahjoittanut,
eikä kenenkään vähempiarvoisemman henkilön kuin hänen katolisen
ja apostolisen majesteettinsa Frans Joosef I:n puolesta.
*** END OF THE PROJECT GUTENBERG EBOOK KEISARIN
KYNTTILÄNJALAT ***

Updated editions will replace the previous one—the old editions will
be renamed.

Creating the works from print editions not protected by U.S.


copyright law means that no one owns a United States copyright in
these works, so the Foundation (and you!) can copy and distribute it
in the United States without permission and without paying copyright
royalties. Special rules, set forth in the General Terms of Use part of
this license, apply to copying and distributing Project Gutenberg™
electronic works to protect the PROJECT GUTENBERG™ concept
and trademark. Project Gutenberg is a registered trademark, and
may not be used if you charge for an eBook, except by following the
terms of the trademark license, including paying royalties for use of
the Project Gutenberg trademark. If you do not charge anything for
copies of this eBook, complying with the trademark license is very
easy. You may use this eBook for nearly any purpose such as
creation of derivative works, reports, performances and research.
Project Gutenberg eBooks may be modified and printed and given
away—you may do practically ANYTHING in the United States with
eBooks not protected by U.S. copyright law. Redistribution is subject
to the trademark license, especially commercial redistribution.

START: FULL LICENSE

You might also like