0% found this document useful (0 votes)
7 views

Laravel Code Smart Dayle Rees download

The document provides links to various Laravel-related ebooks, including 'Laravel Code Smart' by Dayle Rees, which is aimed at beginners and published on May 21, 2016. It also mentions the Lean Publishing process used for the book and encourages sharing on social media. Additional recommended products and resources for Laravel are listed, along with their respective download links.

Uploaded by

mvovodikili
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views

Laravel Code Smart Dayle Rees download

The document provides links to various Laravel-related ebooks, including 'Laravel Code Smart' by Dayle Rees, which is aimed at beginners and published on May 21, 2016. It also mentions the Lean Publishing process used for the book and encourages sharing on social media. Additional recommended products and resources for Laravel are listed, along with their respective download links.

Uploaded by

mvovodikili
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 79

Laravel Code Smart Dayle Rees download

https://ebookbell.com/product/laravel-code-smart-dayle-
rees-5903934

Explore and download more ebooks at ebookbell.com


Here are some recommended products that we believe you will be
interested in. You can click the link to download.

Laravel Code Smart The Laravel Framework Version 5 For Beginners Dayle
Rees

https://ebookbell.com/product/laravel-code-smart-the-laravel-
framework-version-5-for-beginners-dayle-rees-53684112

Laravel 11 Documentation 11th Edition Taylor Otwell

https://ebookbell.com/product/laravel-11-documentation-11th-edition-
taylor-otwell-56620832

Laravel Up Running 3rd Edition Matt Stauffer

https://ebookbell.com/product/laravel-up-running-3rd-edition-matt-
stauffer-53638256

Laravel Starter Shawn Mccool

https://ebookbell.com/product/laravel-starter-shawn-mccool-2624840
Laravel Matt Stauffer Matt Stauffer

https://ebookbell.com/product/laravel-matt-stauffer-matt-
stauffer-30066442

Laravel Application Development Blueprints Arda Kilidagi Halil Ibrahim


Yilmaz

https://ebookbell.com/product/laravel-application-development-
blueprints-arda-kilidagi-halil-ibrahim-yilmaz-4656440

Laravel Up Running A Framework For Building Modern Php Apps Matt


Stauffer

https://ebookbell.com/product/laravel-up-running-a-framework-for-
building-modern-php-apps-matt-stauffer-5473776

Laravel 5 Essentials Explore The Fundamentals Of Laravel One Of The


Most Expressive And Robust Php Frameworks Available Martin Bean

https://ebookbell.com/product/laravel-5-essentials-explore-the-
fundamentals-of-laravel-one-of-the-most-expressive-and-robust-php-
frameworks-available-martin-bean-5473886

Laravel 5x Cookbook Alfred Nutile

https://ebookbell.com/product/laravel-5x-cookbook-alfred-
nutile-7029938
Laravel: Code Smart
The Laravel Framework Version 5 for Beginners

Dayle Rees
This book is for sale at http://leanpub.com/codesmart

This version was published on 2016-05-21

This is a Leanpub book. Leanpub empowers authors and publishers with the Lean
Publishing process. Lean Publishing is the act of publishing an in-progress ebook
using lightweight tools and many iterations to get reader feedback, pivot until you
have the right book and build traction once you do.

© 2014 - 2016 Dayle Rees


Tweet This Book!
Please help Dayle Rees by spreading the word about this book on Twitter!
The suggested tweet for this book is:
I’m learning @laravelphp with #codesmart by @daylerees. Get it at
https://leanpub.com/codesmart
The suggested hashtag for this book is #codesmart.
Find out what other people are saying about the book by clicking on this link to
search for this hashtag on Twitter:
https://twitter.com/search?q=#codesmart
Also By Dayle Rees
Laravel: Code Happy
Laravel: Code Happy (ES)
Laravel: Code Happy (JP)
Laravel: Code Bright
Code Happy (ITA)
Laravel: Code Bright (ES)
Laravel: Code Bright (SR)
Laravel: Code Bright (JP)
Laravel: Code Bright (IT)
Laravel: Code Bright (TR) Türkçe
Laravel: Code Bright (PT-BR)
PHP Pandas (PHP7!)
Laravel: Code Bright (RU)
PHP Pandas (ES)
PHP Pandas (IT)
PHP Pandas (FR)
PHP Pandas (TR)
PHP: Composer
Contents

Acknowledgements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . i

Errata . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ii

Feedback . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . iii

Translations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . iv

How to read this book . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . v


Beginners . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . v
Experienced . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . v
Updates . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . v

Changes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . vii

1. Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1

2. Installation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2
Install Software Dependencies . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2
Create a Laravel Project . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
Install Homestead . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
Mastering Vagrant . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5

3. Valet . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
Installation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
Adding Sites . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
Valet Commands . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
Sharing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9

4. Lifecycle . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
Request . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
Services . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
Routing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
Logic . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
Response . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
CONTENTS

5. Namespaces . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
Global Namespace . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
Simple Name-spacing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
The Theory of Relativity . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
Structure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20
Limitations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20

6. JSON . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22
What is JSON? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22
JSON Syntax . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22
JSON and PHP . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26

7. Composer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29
Configuration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29
Dependency Management . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33
Auto Loading . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40
Installation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 46
Usage . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 46

8. Configuration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 53
Configuration Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 53
Environmental Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 54
Configuration Caching . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 57

9. Basic Routing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 58
Defining Routes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 58
Route Parameters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 63

10. Responses . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 67
Views . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 68
View Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 70
Redirects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 71
Custom Responses . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73

11. Blade Templates . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 80


Building Templates . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 80
Processing PHP . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81
Control Structures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 83
Template Inclusion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 87
Template Inheritance . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 89
Comments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 96
Javascript Support . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 97

12. Request Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 98


Retrieval . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 99
CONTENTS

Old Input . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 106


Uploaded Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 112
Cookies . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 121

13. Facades . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 126


What is a Facade? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 126
How do they work? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 126

14. Advanced Routing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 128


Named Routes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 128
Parameter Constraints . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 130
Route Groups . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 132
Route Prefixing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 132
Domain Routing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 133

15. Controllers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 136


Creating Controllers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 136
Controller Routing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 138
Resource Controllers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 140
Dependency Injection . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 144
Route Caching . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 147

16. URL Generation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 148


The current URL . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 148
Generating Route URLs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 150
Asset URLs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 156

17. Databases . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 158


Abstraction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 158
Configuration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 159
Preparing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 166

18. Schema Builder . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 168


Creating Tables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 168
Column Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 170
Special Column Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 182
Column Modifiers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 184
Updating Tables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 191
Dropping Tables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 197
Schema Tricks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 198

19. Migrations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 202


Basic Concept . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 202
Creating Migrations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 203
Running Migrations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 207
CONTENTS

Rolling Back . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 213


Migration Tricks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 214

20. Eloquent ORM . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 216


Creating new models. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 219
Reading Existing Models . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 227
Updating Existing Models . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 228
Deleting Existing Models . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 232

21. Eloquent Queries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 234


Preparation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 234
Eloquent To String . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 238
Query Structure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 244
Fetch Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 246
Query Constraints . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 258
Magic Where Queries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 278
Query Scopes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 281

22. Eloquent Collections . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 284


The Collection Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 284
Collection Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 285
Best Practice . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 307

23. Eloquent Relationships . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 309


Implementing Relationships . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 314
Relating and Querying . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 320

24. Validation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 325


Simple Validation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 325
Validation Rules . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 335
Error Messages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 344
Custom Validation Rules . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 354
Custom Validation Messages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 357

25. Events . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 361


Concept . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 362
Firing Events . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 362
Listening for Events . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 363
Event Subscribers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 366
Global Events . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 367
Use Cases . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 368

26. Dependency Injection . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 370


Concept . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 370
Dependency Injection with the Container . . . . . . . . . . . . . . . . . . . . . 372
CONTENTS

Injection within Controllers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 373


Injecting Services . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 376
Contracts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 377

27. Middleware . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 382


Middleware Classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 382
Global Middleware . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 388
Route Middleware . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 389
Middleware Parameters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 391
Middleware Groups . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 393

28. Coming Soon . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 395


Acknowledgements
First of all, I would like to thank my girlfriend Emma, for not only putting up with all
my nerdy ventures but also for taking the amazing red panda shots for the books! Love
you, Emma!
Thanks to my parents, who have been supporting my nerdy efforts for close to thirty-
two years! Also, thanks for buying a billion or so copies of the first few books for family
members!
Taylor Otwell, the journey with Laravel has been incredible. Thank you for giving me
the opportunity to be part of the team and for your continued friendship. Thanks for
making a framework that’s a real pleasure to use, makes our code read like poetry, and
for putting so much time and passion into its development.
Thank you to everyone who bought my previous books and to all of the Laravel
community. Without your support, futures titles would not have been possible.

i
Errata
While this may be my fourth book, and my writing is steadily improving, I assure you
that there will be many, many errors. I don’t have a publisher, a review team, or an
English degree. I do the best that I can to help others learn about Laravel. I ask that
you, please be patient with my mistakes. You can support the title by sending an email
with any errors you might have found to [email protected] along with the section
title.
Errors will be fixed as they are discovered. Fixes will be released in future editions of
the book.
1
mailto:[email protected]

ii
Feedback
Likewise, you can send any feedback you may have about the content of the book or
otherwise by sending an email to [email protected] . You can also send a tweet to
@daylerees3 . I will endeavour to reply to all mail that I receive.
2
mailto:[email protected]
3
https://twitter.com/daylerees

iii
Translations
If you would like to translate Code Smart into your language, please send an email to
[email protected] with your intentions. I will offer a 50/50 split of the profits from
the translated copy, which will be priced at the same as the English copy.
Please note that the book is written in markdown format, and is versioned on Github5 .
4
mailto:[email protected]
5
http://github.com

iv
How to read this book
Start with the letters, then the words, then the sentences. Just kidding!

Beginners
If you’re new to Laravel, you’ll want to read through the book as you would any other.
Each chapter will lead into the next, and they have been ordered in a fashion that will
make the learning process as simple as possible.
You don’t need any prior Laravel knowledge, but you should have an understanding of
the PHP language. If you’ve never used PHP, I’d suggest reading my other book ‘PHP
Pandas’ first. It’s available on Leanpub.com6 .

Experienced
Experienced developers will find Code Smart useful as a reference book. The chapters
have been named in a format to make ‘skimming’ the book for content much more
simple than in previous versions. Simply find the topic in the index, navigate to the
chapter, and skim the examples until you find what you need.
As always, you’ll find much more advanced topics at the end of the book. New topics
will be added as we move forward, see the next chapter.

Updates
My books are hosted on Leanpub, and I do this for good reason. It’s not that I prefer to
self-publish, but instead, the flexibility that Leanpub give. Leanpub allows for books to
be published while in progress. What this means is that you can release either partial
content, or publish additional chapters at a later date.
Laravel, as a framework, will evolve. I believe that the book should evolve with it. For
that reason, it’s important that you download the latest copy of the book at a regular
interval. If you want to stay informed as new topics and changes are released, then
you’ll find that I post most of my update on my Twitter profile7 . You’ll also receive an
email whenever a new version of the book is published.
6
https://leanpub.com/php-pandas
7
https://twitter.com/daylerees

v
How to read this book vi

New topics will be added to the book at regular intervals. At launch, the book will
contain all of content that was present in Code Bright, refreshed and updated for the
new framework version, plus a bunch of additional new chapters. I’m committing to
delivering at least one chapter per week, expanding the book until it’s the ‘Encyclo-
pedia Laravelica’.
If you’d like to suggest a chapter to cover next, think a topic is missing, or would like
something explained in further detail, then please contact me at [email protected] .
Let’s build this masterpiece together!
8
mailto:[email protected]
Changes
Developers love to keep change logs, don’t they? They contain everything that they’ve
changed in their code, date by date. Since this is a book that is in constant evolution,
I have decided to do the same with Code Smart. In this chapter, you’ll find all of the
changes made to the book, including new content that has been released, and where
to find it.

27th April 2016


Code Smart was released. The book includes updated (and refreshed) content from
Code Bright, and some chapters that are unique to Laravel 5. The preparatory process
has been redesigned from the ground up to make the learning process more simple.
Enjoy!

vii
1. Introduction
Why hello there! Pleased to meet you.
My name is Dayle, and I’m a developer. I’ve just started my fourth decade on this
planet, and I hail from the pleasant land of Wales. Many years ago, I was one of
the first to use a brand new framework for the PHP programming language called
‘Laravel.’ From the first read of the documentation, I knew that I had to start building
applications with it. It was clean, concise and beautiful. I saw great potential in the
framework, and I think I was right!
Since then, I’ve been a core contributor, a conference speaker, a consultant, and an
author of several books based on the Laravel framework. The books have received an
astounding reaction, and have thousands of fans worldwide! It’s been an incredible
experience. If you’ve read one of my books before, then thank you so much! If not,
well, let me take a moment to explain how this works.
You see, I’m not a traditional author. I don’t like making things complicated. I don’t
like using posh words to make myself sound smart, and I write my books as if we’re
sharing an adventure of discovery. I’ve said it before, and I’ll say it again; I like to write
my books as if we’re two friends, sitting in a bar, sharing a drink and a conversation.
Just so long as long as you’re getting a round in!
This title is the third in my Laravel series, and it covers version 5.x of the Laravel
framework. I’ve learned a little more about writing technical books with every one
that I’ve released, and so, I hope you find reading this book an enjoyable experience.
If there’s anything you don’t like about the book or if there’s a chapter or concept
that’s not as clear as it could be, then please send me an email! I’m very responsive. In
fact, I pride myself on it! For this book to be as perfect as it can be, I’m going to need
your feedback. Let’s write this masterpiece together!
Right then, you’re probably excited to get started aren’t you? It’s a big framework, but
I promise that if we take it step by step, you’ll be building great apps in no time at all!
Are you prepared? Go ahead, flip the page.

1
2. Installation
I’m sure you’re eager to get started with Laravel. Since it’s a web framework, it’s impor-
tant that we create an environment with a web-server. In a production environment,
this would take a long time to configure, and would rely on a unix-based platform, so
let’s build a homestead instead.

This is no time for home-making!

Hah! You might be right, but that’s not quite what we mean in this instance. A
‘Homestead’ is a virtualised web application environment powered by a piece of
software called ‘Vagrant.’ It can get us up and running on Laravel in a jiffy!
Homestead is my preferred option of running Laravel. It ships with all the software
required to launch the framework, however, it is one extra piece of software to learn.
You’ll need to remember to SSH into the virtual machine and run your commands
from there. For this reason, the next chapter will introduce ‘Valet’. Valet is a binary
that will allow you to run web applications using a version of PHP installed on your
computer. Right now, it’s only available on Mac. If you’re not using a Mac, or you’d like
to take my advice, then please continue reading. Otherwise, feel free to skip to the
next chapter to use Valet instead.

Install Software Dependencies


Before we can get our homestead running, we’re going to need to install a few
dependencies. Here’s the full list.

• PHP http://www.php.net/1
• Git https://git-scm.com/2
• Composer https://getcomposer.org/3
• Virtualbox https://www.virtualbox.org/4
• Vagrant https://www.vagrantup.com/5
1
http://www.php.net/
2
https://git-scm.com/
3
https://getcomposer.org/
4
https://www.virtualbox.org/
5
https://www.vagrantup.com/

2
Installation 3

I’m not going to provide specific installation instructions because they change from
week to week. Instead, head over to the URLs above and you’ll find sections of each
site that will cover download and installation instructions for your operating system.
Let’s take a look at what each piece of software offers.
We’re going to need ‘PHP’. It’s the language used by the Laravel framework. There’s
no way of getting out of this one! Download the latest version that’s available.
We’ll use ‘Git’ for version control. It’s also a great way of downloading a base copy
of Laravel. It’s worth having since it’s a day-to-day part of any experienced software
developer’s workflow.
We’ll use ‘Composer’ to manage all the libraries that we use with PHP. Go ahead and
grab it. It’s one of my favorite pieces of software!
Next, we have ‘Virtualbox’. It’s software that will allow operating system virtualisation.
Essentially, this will allow you to run ‘pretend’ computers on your main computer.
Since web development setups run best on unix environments, we’ll be using a virtual
unix environment so that we can develop on any platform!
Finally, we have ‘Vagrant’. Vagrant is used to provision virtual environments, and to
configure them the way that we want them. It’s a command line program, so we’ll be
using it in the terminal. Vagrant will be making use of Virtualbox to create project
environments.
Once we’ve got all five pieces of software installed, we’re ready to move to the next
section.

Create a Laravel Project


Before we build our homestead, we’ll need to have a Laravel project ready for it.
First, we’ll need to decide on a disk location for your projects. I’m going to be creating
a ‘Projects’ directory in my home folder. This is where all my Laravel projects will live.
Let’s start by navigating to our projects folder, shall we?

Example 01: Navigate to projects directory.

1 cd ~/Projects

That wasn’t so hard, was it? Next, we can use the ‘Composer’ software that we installed
earlier to create a new Laravel project. Let’s type the following command and see what
happens. You can replace the word ‘example’ with your project name if you’d prefer
something different.
Installation 4

Example 02: Create a Laravel project.

1 composer create-project laravel/laravel example

You’ll see a lot of output. This is where Composer is downloading all of the libraries
that support Laravel. We call these ‘package dependencies’. Once complete, you’ve
installed Laravel. Continue to the next section to add a homestead.

Install Homestead
First, let’s navigate to the directory that our Laravel project is contained within.

Example 03: Navigate to the project directory.

1 cd ~/Projects/example

Next, we’re going to install the homestead composer package, so that we can create
a homestead virtual environment. Don’t worry; it’s simple. Just type the following
command.

Example 04: Add homestead to composer dependencies.

1 composer require laravel/homestead --dev

You’ll see a few more composer packages installed in the output of the command.
Don’t worry. That’s what we want!
Next, we’ll run the ‘make’ command, to configure our project for homestead. Here’s
the full command.

Example 05: Install homestead.

1 php vendor/bin/homestead make

Well, at least that one was super quick!


Next, it’s time for the long one. Let’s use the following command to boot up a virtual
machine. If it’s the first time that you’re running this command, it’s going to take a
while to download the virtual machine image. It’s around 600mb or so. Go and make
yourself a coffee!
Installation 5

Example 06: Boot the virtual machine.

1 vagrant up

Once the virtual machine has come online, there’s one final thing you’re going to
need to do. We’ll add the homestead app domain to our hosts file so that we can
conveniently access our web application in the browser.
Use your favorite editor to edit the file at /etc/hosts. You’re going to need admin/root
privileges to access this file. You’ll want to add the following line.

Example 07: Add a local DNS entry.

1 192.168.10.10 homestead.app

To check whether everything is working, let’s visit http://homestead.app in our


browser. You should see the text ‘Laravel 5’. That’s our Laravel application!

Mastering Vagrant
Your brand new web development environment exists on a virtual machine, and that
machine is draining the resources of your host machine. For example, it will share
your available RAM and processor time.
From time to time, it might be useful to be able to ‘halt’ and restore our environment
to save system resources. It’s also noting that when we restart our host computer, our
virtual environment will not boot automatically.
For this reason, let’s go over a few basic commands to maintain our Vagrant environ-
ments. We’ll be using these commands in the directory containing the Vagrantfile
file.
The first command is used to start your virtual machine. You’ve already used it. Here’s
an example.

Example 08: Boot the virtual machine.

1 vagrant up

The second command is the exact opposite. It’s used to halt your virtual machine. It
will no longer be using system resources. You’re going to want to use the following.
Installation 6

Example 09: Halt the virtual machine.

1 vagrant halt

If you decide to change the configuration of your Vagrant box by updating the
Vagrantfile, you’re going to want to use ‘provision’ to apply the changes to the virtual
machine.

Example 10: Update the virtual machine settings.

1 vagrant provision

In some circumstances, you may want to run commands on the guest virtual machine.
You can easily access this machine by using the Vagrant SSH command. This will allow
you sudo access to the guest. For example.

Example 11: SSH into the virtual machine.

1 vagrant ssh

Finally, if we’re done with our project, and don’t want the virtual machine image
hogging our disk space, we can ditch it! Just use the ‘destroy’ command!

Example 12: Destroy the virtual machine.

1 vagrant destroy

In the next chapter, we’ll take a look at an alternative way of running a Laravel
application.
3. Valet
Laravel is a piece of software that exists within the Laravel ecosystem to allow you to
run web applications using the stack that is already installed on your development
machine. For example, you might already have PHP installed locally, or a copy of
MariaDB to use as a database. Homestead would run a VM containing many types
of software that can be used with Laravel, but with Valet; you install only what you
need.
Personally, I would recommend using Homestead, as it will allow you to version your
running environment alongside your code. This is an incredibly useful advantage,
especially when working within a team. However, it is understood that Homestead
is more complicated than Valet.
If you’re not comfortable with Homestead, the continue reading to learn how to be
up and running with Valet in no time at all.

Installation
Since Valet uses the software on your computer to run its stack, then you’ll first need
to install at least PHP. Remember, Valet will only work on a Mac, so if you’re using a
Windows or Linux machine, then I’d just skip to the next chapter at this point.
On a Mac, PHP can be installed using the ‘Homebrew’ software. It would be best to
check the Homebrew website1 for instructions on how to install the software. Once
it’s installed, you can install PHP using the following command:

Example 01: Install PHP with Homebrew.

1 brew install homebrew/php/php70

Once you’ve got your copy of PHP installed, we’ll continue to install the Valet
binary. This can be achieved using Composer. If you’d like to find out how to install
Composer, then please check the previous chapter. It would be pointless to repeat this
information, wouldn’t it?! We are programmers after-all. We hate repeating ourselves!
We’ll install Valet globally by running the following command:

1
http://brew.sh/

7
Valet 8

Example 02: Install Valet using Composer.

1 composer global require laravel/valet

You may need to add Composer’s binary path to your system PATH variable. You’ll be
able to do that for the current session using the following command.

Example 03: Add Composer to system path.

1 export PATH="$PATH:$HOME/.composer/vendor/bin"

Next, install the Valet service with the following command.

Example 04: Install the Valet service.

1 $ valet install
2
3 WARNING: Improper use of the sudo command could lead to data loss
4 or the deletion of important system files. Please double-check your
5 typing when using sudo. Type "man sudo" for more information.
6
7 To proceed, enter your password, or type Ctrl-C to abort.
8
9 Password:
10 [dnsmasq] is not installed, installing it now via Brew...
11
12 Valet installed successfully!

Great! Valet is now installed. Let’s start using it, shall we?

Adding Sites
Valet is fully equipped to serve multiple applications, so first we’ll need to ‘park’ our
application directory. Let’s say that we’re storing our projects in ∼/projects. We’ll
navigate to the projects folder and create a new Laravel project using Composer. We’ll
call our project ‘blog’ for example purposes.
Valet 9

Example 05: Create a new Laravel project.

1 $ composer create-project laravel/laravel blog

Next, we’ll navigate to and park our applications directory.

Example 06: Park our project directory.

1 $ cd ~/projects
2 $ valet park
3 This directory has been added to Valet's paths.

That’s it; you’re done! Honestly!


You see, any project within your parked directory will be served under the host-
name projectname.dev. For example, the blog we created above will be accessible at
blog.dev. If you visit the URL, you’ll see the Laravel welcome page.

Don’t forget to install some database software if you’d like to store information later.
Do you see why I prefer homestead yet? Well, each to their own I suppose!

Valet Commands
If you’d like to start, stop or restart the valet daemon that is serving your applications,
then the following commands are available.

Example 07: Valet service commands.

1 $ valet stop
2 $ valet start
3 $ valet restart

Sharing
Valet offers a useful shortcut to be able to share your applications with others. Please
note that this is a tool for collaboration and that you shouldn’t use this to serve your
applications for the long-term! Simply use the share command as follows:
Valet 10

Example 08: Share a Valet application.

1 $ cd ~/projects/blog
2 $ valet share

On the screen that appears, you’ll find a ‘Forwarding’ URL that can be used to share
your applications with others. You’ll also see the requests as they pour into your
application.

If you’d like to use this sharing feature with Homestead, or any other stack,
then take a look at the ‘ngrok’ website2 .

We’ve now got everything we need to start working with Laravel. It looks like it’s time
to move on to something new. In the next chapter, we’ll take a look at the lifecycle of
a modern PHP application. Do your best superhero pose and flip that page.
2
https://ngrok.com/
4. Lifecycle
If you’ve not used a PHP framework before, then you’ll likely be used to having a bunch
of different PHP files in your web directory. The person using your web application
will request each script individually.
Laravel uses a front-controller and router combination. What this means is that
there’s only a single PHP file in your web root directory, and all requests to your
application will be made through this script. This file is called index.php and you’ll
find it in the public directory, which is the only directory that should be accessible
on the web.

I can’t make a web application with one page!

Don’t worry. We’ve got a solution to that. You see, Laravel uses some different
techniques to serve different content based on the state of the web-browser request.
In fact, here’s a diagram to display the lifecycle of a single request to a Laravel
framework application.

1 Request > Services > Routing > Logic > Response

In a way, a request to a webserver is an input/output loop. In honesty, there are a few


more steps involved, but this isn’t the place to discuss them! Let’s step through each
section of the process, shall we?

Request
Every request made by a web browser to your application has a broad range of
information attached to it. For example, the URL, the HTTP method, request data,
request headers, and information about the source of the request.
It’s up to Laravel, and your application to interrogate the information within the
request, to decide which action to perform. Using Laravel, the information for the
current request is stored in an instance of the class Illuminate\Http\Request, which
extends from the Symfony Framework Symfony\Component\HttpFoundation\Request
class.
You see, the Symfony Framework has a fantastic implementation of the HTTP protocol
in its ‘HTTP Foundation’ package. Laravel makes use of this package to avoid re-
inventing a wheel.
We now have a request, and so we have all the information we need for our application
to decide on an appropriate action. So, what’s next? Let’s take a look.

11
Lifecycle 12

Services
The next step in the process is the bootstrapping of the framework. Laravel ships with
a bunch of services and features that make our lives as web developers considerably
easier! Before we can make use of these services, they need to bootstrapped.
The framework will load all defined services and configuration, and ensure that it has
everything it needs to support our code. We’ll take a closer look at how services are
loaded within the ‘Service Providers’ chapter.
The framework is now ready for our code, but which piece of code should it run? Let’s
find out!

Routing
As we have discovered previously, there’s only a single script that’s accessible when
using Laravel. How do we show different pages, or make different actions? That’s
where the router makes an appearance!
The router’s sole purpose is to match up a request to the appropriate piece of code
to execute. For example, the router will know that it should run the code to display
a users profile page when the request includes a HTTP verb of ‘GET’ and a URI of
‘/user/profile’.
Laravel has a nice way of defining these routes, and we’ll be looking at that very soon.
For now, let’s take a look at what happens next.

Logic
Next, we have our logic segment. This section can best be described as your code. It’s
where you’ll be talking to a database, validating forms, or showing pages.
In Laravel, we’ve got some different ways of defining your logic, but we’ll be looking
at this in a later chapter. For now, let’s take a look at the final section, shall we? I know
our application users will be eager for this one!

Response
The response is created at the end of your logic. It might be a HTML template. It might
be some JSON data; it might just be a string. Hey, it might be nothing at all. In some
sad circumstances, it might be an error screen or a 404 page! It’s good to have options,
isn’t it?
Lifecycle 13

The response is what your application users will see. It’s the part that they are most
excited about!
Let’s summarize, shall we?
The web browser sends a request. Laravel bootstraps its services, interrogates the
request, and performs routing operations. Our code is executed and delivers a
response to the user. It’s a wonderful smooth operation, isn’t it?
It sounds like a very simple process, but I promise that keeping these “flows” in your
mind, will make you a better web developer.
Let’s turn up the music, and keep this party going in the next chapter! We’re going
to be looking at the MVC (Model View Controller) software architecture pattern. It’s
used by plenty of Laravel apps, so I think it’s worth reading!
5. Namespaces
In version 5.3 of PHP, a new feature known as name-spacing was added to the
language. Many modern languages already had this feature for some time, but PHP
was a little late to the scene. None the less, every new feature has a purpose. Let’s
find out why PHP namespaces can benefit our application.
You can’t have two classes that share the same name. They have to be unique. The
issue with this restriction is that if you are using a third party library which has a
class named User, then you can’t create your own class also called User. This is a real
shame because that’s a pretty convenient class name, right?
PHP namespaces allow us to circumvent this issue. In fact, we can have as many User
classes as we like. Not only that, but we can use namespaces to contain our similar
code into neat little packages, or even to show ownership.
Let’s take a look at a normal class. Yes. I know you have used them before. Just trust
me on this one, okay?

Global Namespace
Here’s a simple class.

Example 01: A simple class.

1 <?php
2
3 // app/Eddard.php
4
5 class Eddard
6 {
7
8 }

There’s nothing special about it. If we want to use it then, we can do this.

14
Namespaces 15

Example 02: Using the class.

1 <?php
2
3 // app/Http/routes.php
4
5 $eddard = new Eddard;

Dayle, I know some PHP…

Okay, okay. Sorry.


We can think of this class as being in the ‘global’ namespace. I don’t know if that’s the
right term for it, but it sounds quite fitting to me. It essentially means that the class
exists without a namespace. It’s just a normal class.

Simple Name-spacing
Let’s create another class alongside the original, global Eddard.

Example 03: Name-spaced class.

1 <?php
2
3 namespace Stark;
4
5 // app/another.php
6
7 class Eddard
8 {
9
10 }

Here we have another Eddard class, with one minor change. The addition of the
namespace directive. The line namespace Stark; informs PHP that everything we do
is relative to the Stark namespace. It also means that any classes created within this
file will live inside the ‘Stark’ namespace.
Let’s try to use the ‘Eddard’ class once again.
Namespaces 16

Example 04: Using a class.

1 <?php
2
3 // app/Http/routes.php
4
5 $eddard = new Eddard;

Once again, we get an instance of the first class we created in the last section. Not
the one within the ‘Stark’ namespace. Let’s try to create an instance of the ‘Eddard’
within the ‘Stark’ namespace.

Example 05: Using a class in Stark.

1 <?php
2
3 // app/Http/routes.php
4
5 $eddard = new Stark\Eddard;

We can instantiate a class within a namespace, by prefixing it with the name of


the namespace, and separating the two with a backward (\) slash. Now we have an
instance of the ‘Eddard’ class within the ‘Stark’ namespace. Aren’t we magical?!
You should know that namespaces can have as many levels of hierarchy as they need
to. For example.

Example 06: A horrible namespace.

1 This\Namespace\And\Class\Combination\Is\Silly\But\Works

The Theory of Relativity


Remember how I told you that PHP always reacts relative to the current namespace?
Well, let’s take a look at this in action.
Namespaces 17

Example 07: Instantiate within namespace.

1 <?php
2
3 namespace Stark;
4
5 // app/Http/routes.php
6
7 $eddard = new Eddard;

By adding the namespace directive to the instantiation example, we have moved the
execution of the PHP script into the ‘Stark’ namespace. Since we are inside the same
namespace as the one we put ‘Eddard’ into, we receive the name-spaced ‘Eddard’
class. See how it’s all relative?
Now that we have changed the active namespace, we have created a little problem.
Can you guess what it is? How do we instantiate the original ‘Eddard’ class? The one
not in the namespace.
Fortunately, PHP has a trick for referring to classes that are located in the global
namespace. We simply prefix them with a backward (\) slash.

Example 08: Instantiate class from root namespace.

1 <?php
2
3 // app/Http/routes.php
4
5 namespace Stark;
6
7 $eddard = new \Eddard;

With the leading backward (\) slash, PHP knows that we are referring to the ‘Eddard’
in the global namespace, and instantiates that one.
Use your imagination a little, like how Barney showed you. Imagine that we have
another namespaced class called Tully\Edmure. Now we want to use this class from
within the ‘Stark’ framework. How do we do that?
Namespaces 18

Example 09: Instantiate class in other namespace.

1 <?php
2
3 namespace Stark;
4
5 // app/Http/routes.php
6
7 $edmure = new \Tully\Edmure;

One again, we need the prefixing backward slash to bring us back to the global
namespace before instantiating a class from the ‘Tully’ namespace.
It could get tiring referring to classes within other namespaces by their full hierarchy
each time. Luckily, there’s a nice little shortcut we can use. Let’s see it in action.

Example 10: Use a foreign class.

1 <?php
2
3 namespace Stark;
4
5 use Tully\Edmure;
6
7 // app/Http/routes.php
8
9 $edmure = new Edmure;

Using the use statement, we can bring one class from another namespace into the
current namespace. This will allow us to instantiate it by name only.
We can give our imported classes little nicknames like we used to in the PHP
playground. Let me show you.
Namespaces 19

Example 11: Class alias.

1 <?php
2
3 namespace Stark;
4
5 use Tully\Brynden as Blackfish;
6
7 // app/Http/routes.php
8
9 $edmure = new Blackfish;

By using the ‘as‘ keyword, we have given our ‘Tully/Brynden’ class the ‘Blackfish’
nickname. This will allow us to use the new nickname to identify it within the current
namespace. Neat trick, right? It’s also really handy if you need to use two similarly
named classes within the same namespace. For example.

Example 12: The mother of twin classes.

1 <?php
2
3 namespace Targaryen;
4
5 use Dothraki\Daenerys as Khaleesi;
6
7 // app/Http/routes.php
8
9 class Daenerys
10 {
11
12 }
13
14 // Targaryen\Daenerys
15 $daenerys = new Daenerys;
16
17 // Dothraki\Daenerys
18 $khaleesi = new Khaleesi;

By giving the ‘Daenerys’ within the ‘Dothraki’ namespace a nickname of ‘Khaleesi’, we


can use two ‘Daenerys’ classes by name only. Handy, right? The game is all about
avoiding conflicts and grouping things by purpose or faction.
You can use as many classes as you need to.
Namespaces 20

Example 13: Using multiple classes.

1 <?php
2
3 namespace Targaryen;
4
5 use Stark\Eddard;
6 use Lannister\Tyrion;
7 use Dothraki\Daenerys;
8 use Snow\Jon as Bastard;

Structure
Namespaces aren’t just about avoiding conflicts. We can also use them for organiza-
tion and ownership. Let me explain with another example.
Let’s say I want to create an open source library. I’d love for others to use my
code; it would be great! The trouble is, I don’t want to cause any problematic class
name conflicts for the person using my code. That would be terribly inconvenient.
Here’s how I could avoid causing hassle for the wonderful, open source embracing,
individual.

Example 14: Vendor prefixing.

1 Dayle\Blog\Content\Post
2 Dayle\Blog\Content\Page
3 Dayle\Blog\Tag

Here we have used my name to show that I created the original code, and to separate
my code from that of the person using my library. Inside the base namespace, I have
created some sub-namespaces to organize my application by its internal structure.
In the composer section, you will learn how to use namespaces to simplify the act of
loading class definitions. I strongly suggest you take a look at this useful mechanism.

Limitations
In truth, I feel a little guilty for calling this sub-heading ‘Limitations.’ What I’m about
to talk about isn’t a bug.
You see, in other languages, namespaces are implemented in a similar way. Those
other languages provide an additional feature when interacting with namespaces.
Namespaces 21

In Java, for example, you can import some classes into the current namespace by using
the import statement with a wildcard. In Java, ‘import’ is equivalent to ‘use’, and it uses
dots to separate the nested namespaces (or packages). Here’s an example.

Example 15: Java imports.

1 import dayle.blog.*;

The above would import all of the classes that are located within the ‘dayle.blog’
package.
In PHP, you simply can’t do that. You have to import each class individually. Sorry
about that. Actually, why am I saying sorry? Go and complain to the PHP internals
team instead. Only, be gentle. They have given us a lot of cool stuff recently.
Here’s a neat trick you can use. Imagine that we have this namespace and class
structure, as in the previous example.

Example 16: My blog.

1 Dayle\Blog\Content\Post
2 Dayle\Blog\Content\Page
3 Dayle\Blog\Tag

We can give a sub-namespace a nickname, to use it’s child classes. Here’s an example.

Example 17: Nickname a sub-namespace.

1 <?php
2
3 namespace Baratheon;
4
5 use Dayle\Blog as Cms;
6
7 // app/Http/routes.php
8
9 $post = new Cms\Content\Post;
10 $page = new Cms\Content\Page;
11 $tag = new Cms\Tag;

This should prove useful if you need to use many classes within the same namespace.
Enjoy!
Next, we will learn about Jason. No. Not Jason Lewis the Aussie scoundrel, but JSON
strings. Just turn the page and you’ll see what I mean!
6. JSON
What is JSON?
For the next chapter on Composer, we’re going to need a basic understanding of
JSON. Trust me; it doesn’t hurt to learn this stuff. JSON is used by a bunch of different
technologies.
JSON stands for JavaScript Object Notation. It was named this way because JavaScript
was the first language to take advantage of the format.
Essentially, JSON is a human readable method of storing arrays and objects with values
as strings. It is used primarily for data transfer and is a lot less verbose than some of
the other options such as XML.
Commonly, it is used when the front-end part of your application requires some data
from the back-end without a page reload. This is commonly achieved using JavaScript
with an AJAX or ‘XHR’ request.
Many software APIs also serve content using this file format. Twitter’s own is an
excellent example of such an API.
Since version 5.2.0, PHP has been able to serialise objects and arrays to JSON. This is
something I have personally abused a billion or so times and was a great addition to
the language.
If you have been working with PHP for a while, you may have already used its
serialize() method to represent a PHP object as a string. You are then able to use
the unserialize() method to transform the string into a new instance containing the
original value.
It’s what we will be using JSON for. However, the advantage is that JSON can be parsed
by a variety of different languages, where serialize()d strings can only be parsed
by PHP. The additional advantage is that we (as humans and pandas) can read JSON
strings, but PHP serialised strings will look like garbage.
Enough back story. Let’s dive right in and have a look at some JSON.

JSON Syntax

22
JSON 23

Example 01: Sample JSON.

1 {"name":"Lushui","species":"Panda","diet":"Green Things","age":7,"colours":["red\
2 ","brown","white"]}

Yay! JSON! Okay. When I said it was readable to humans, I may have forgotten to
mention something. By default, JSON is stored without any white space between its
values. This might make it a little more difficult to read.
This is normally used to save on bandwidth when transferring the data. Without all
the extra whitespace, the JSON string will be much shorter and thus be fewer bytes
to transfer.
The good news is that JSON doesn’t care about whitespace or line breaks between
its keys and values. Go wild! Throw all the white space you want in there to make it
readable.
Sure, we could do this by hand (let’s not), but there are plenty of tools out there on
the web to beautify JSON. I won’t choose one for you. Go hunting! You might even
find extensions for your web browser to allow you to read JSON responses from web
servers more easily. I highly recommend finding one of these!
Let’s add some whitespace to the JSON from before to make it easier to read.
(Honestly, I did do this by hand. Don’t try this at home folks.)

Example 02: Beautiful JSON.

1 {
2 "name": "Lushui",
3 "species": "Panda",
4 "diet": "Green Things",
5 "age": 7,
6 "colours": ["red", "brown", "white"]
7 }

Aha! There we go. We now have a JSON string representing the red panda that lives
on the cover of my books. Lushui safely guards your Laravel knowledge against prying
eyes.
As you can see from the example, we have some key-value pairs. Within one of the key-
value pairs, we have an array. If you have used some JavaScript before you may wonder
what has changed here? In fact, let’s have a look at how this would be represented in
JavaScript.
JSON 24

Example 03: A JavaScript object.

1 var lushui = {
2 name: 'Lushui',
3 species: 'Panda',
4 diet: 'Green Things',
5 age: 7,
6 colours: ['red', 'brown', 'white']
7 };

Hopefully, you will have spotted some similarities between the JavaScript and JSON
snippets.
The JavaScript snippet is assigning an object literal to a variable, like this:

Example 04: Object assignment.

1 var lushui = { .. };

JSON is a data transfer format and not a language. It has no concept of variables. This
is why you don’t need the assignment within the JSON snippet.
The method of representing an object literal is very similar. This is no coincidence! As
I said before, JSON was originally invented for use with JavaScript.
In both JSON and JavaScript, objects are contained within { two curly braces }
and consist of key-value pairs of data. In the JavaScript variant, the keys didn’t
require quotes because they represent variables, but we know that JSON doesn’t have
variables. This is fine since we can use strings as keys, and that’s what JSON does to
work around this problem.
You may also have noticed that I used single quotes around the JavaScript values. This
is a trap! That behaviour is perfectly acceptable with JavaScript, but JSON strings must
be contained within double quotes. You must remember this, young padawan!
In both JavaScript and JSON, key-value pairs must be separated with a colon (:), and
sets of key-value pairs must be separated by a comma (,).
JSON will support strings and numerical types. You can see that the value for Lushui’s
age is set to an integer value of seven.

Example 05: Wise old Lushui.

1 age: 7,

JSON will allow the following value types.


JSON 25

• Double
• Float
• String
• Boolean
• Array
• Object
• Null

Numeric values are represented without quotes. Be careful when choosing whether
to quote a value or not. For example, US zip codes consist of five numbers. However, if
you were to omit the quotes from a zip code, then 07702 would act as an integer and be
truncated to 7702. This has been a mistake that has taken many a life of a web-faring
adventurer.
Booleans are represented by the words true and false, both without quotes much
like PHP itself. As I said previously, string values are contained within double quotes
and not single quotes.
The null value works in a similar way to PHP and is represented by the word null
without quotes. This should be easy to remember!
We have seen objects. Much like the main JSON object itself, they are wrapped with
curly braces and can contain all sorts of value types.
Arrays look very similar to their JavaScript counterpart.

Example 06: A JavaScript Array.

1 // JavaScript
2 ['red', 'brown', 'white']

Example 07: A JSON array.

1 ["red", "brown", "white"]

You will notice that I didn’t add an inline comment for the JSON snippet in
the above example. That’s because JSON doesn’t support commenting since
it’s used for data transfer. Keep that in mind!

As you can see, the arrays for both are wrapped within [ square braces ], and contain
a list of comma (,) separated values with no indexes. The only difference is that double
quotes must be used for strings within JSON. Are you getting bored of me saying that
yet?
JSON 26

As I mentioned above, the values that can be contained within JSON include both
objects and arrays. The clever chaps amongst my readers (aka all of you) may have
realised that JSON can support nested objects and arrays. Let’s have a look at that in
action!

Example 08: Nesting.

1 {
2 "an_object": {
3 "an_array_of_objects": [
4 { "The": "secret" },
5 { "is": "that" },
6 { "I": "still" },
7 { "love": "shoes!" }
8 ]
9 }
10 }

Okay. Take a deep breath. Here we have a JSON object containing an object containing
an array of objects. This is perfectly fine, and will allow JSON to represent some
complex data collections.

JSON and PHP


As mentioned previously since version 5.2.0 PHP has provided support for serialising
and unserializing data to and from the JSON format. Let’s go ahead and have a look at
that in action.

Serialise a PHP array to JSON


To serialise a PHP value we need only use the json_encode() method.

Example 09: Serialise an array.

1 <?php
2
3 $truth = ['panda' => 'Awesome!'];
4 echo json_encode($truth);

The result of this snippet of code would be a JSON string containing the following
value.
JSON 27

Example 10: Output.

1 {"panda":"Awesome!"}

Great! That’s more like it. Let’s make sure that we can convert this data back into a
format that can be understood by PHP.

Unserialise a PHP array from JSON


For this we will use the json_decode() method. I bet you didn’t see that one coming?

Example 11: Unserialise a JSON string.

1 <?php
2
3 $truth = json_decode('{"panda":"Awesome!"}');
4 echo $truth['panda'];

Awesome! We go… wait. What?

Example 12: Error.

1 Fatal error: Cannot use object of type stdClass as array in ...

You see, the json_decode() method doesn’t return our JSON as a PHP array; it uses a
stdClass object to represent our data. Let’s instead access our object key as an object
attribute.

Example 13: Object access.

1 <?php
2
3 $truth = json_decode('{"panda":"Awesome!"}');
4 echo $truth->panda;
5
6 // Awesome!

Great! That’s what we wanted. If we wanted an array instead, then PHP provides some
ways to convert this object into one, but fortunately json_decode() has another trick
up its sleeve!
If you provide true as the second parameter to the function, we will receive our PHP
array exactly as expected. Thanks json_decode()!
JSON 28

Example 14: Array access.

1 <?php
2
3 $truth = json_decode('{"panda":"Awesome!”}', true);
4 echo $truth['panda'];
5
6 // Awesome!

Huzzah!
So you might be wondering why I just wrote a gigantic chapter on JSON within a
Laravel book. Furthermore, you are probably asking why I’m choosing to answer this
question at the end of the chapter!?
It’s just more fun that way.
In the next section, we will be taking a look at the package manager for PHP. When
we start looking at Composer, you will understand why a knowledge of JSON is so
important.
7. Composer
In this chapter, we’re going to take a pause from Laravel to examine another tool in
the PHP world. Don’t worry. Laravel does make use of this tool, so if you stick it out,
it will make you a better Laravel developer.
Composer is something special in the world of PHP. It has changed the way we handle
application dependencies and quelled the tears of many PHP developers.
You see, in the olden days, when you wanted to build an application that relied on
third party dependencies you would have to install them with PEAR or PECL. These
two dependency managers both have a very limited set of outdated dependencies and
have been a thorn in the side of PHP developers for a long time.
When a package is finally available, you could download a particular version, and it
would be installed on your system. However, the dependency is linked to PHP rather
than your application itself. What this means is that if you had two applications that
required different versions of the same dependencies… well, you’re gonna have a bad
time.
Enter Composer, king of the package managers. First, let’s think about packages. What
are they?
Let’s forget about the concept of ‘applications’ and ‘projects’ for now. The tool that you
are building is called a package. Imagine a little box containing everything needed to
run your application.
This box requires only one piece of paper (file) inside for it to be registered as a
package.

Configuration
You have learned about JSON in the last chapter, right? You are ready for this now!
Remember that I told you JSON was used for data transfer between web applications?
Well, I lied. It’s not that I’m nasty. It just made it easier to teach the topic with a smaller
scope of its ability. I do this a lot. Expect many lies!
Do you remember how JSON represents a complex piece of data? Why can’t we use
it within flat files to provide configuration? That’s precisely what the Composer guys
thought. Who are we to argue with them?
JSON files use the .json extension. Composer expects its configuration to live at the
root of your package using the filename composer.json. Remember this! Laravel will
use this file often.

29
Composer 30

Let’s open it up and start entering some information about our package.

Example 01: Composer.json.

1 {
2 "name": "marvel/xmen",
3 "description": "Mutants saving the world for people who hate them.",
4 "keywords": ["mutant", "superhero", "bald", "guy"],
5 "homepage": "http://marvel.com/xmen",
6 "time": "1963-09-01",
7 "license": "MIT",
8 "authors": [
9 {
10 "name": "Stan Lee",
11 "email": "[email protected]",
12 "homepage": "http://marvel.com",
13 "role": "Genius"
14 }
15 ]
16 }

Right. Here we have a composer.json file at the root of a package for the X-Men. Why
the X-Men? They are awesome. That’s why.
Truth be told, all of the options (keys) in this file are optional. You would usually
provide the above information if you intended to redistribute the package or release
it into the wild.
To be quite honest with you, I normally go ahead and fill in this information. It doesn’t
do any harm. The configuration above is used to identify the package. I have omitted
a few keys that I felt were reserved for special circumstances. If you are curious about
any additional config, then I would recommend checking out the Composer website1
which contains a wealth of information and documentation.
I also found this handy cheat sheet2 online, which may be useful for newcomers to
Composer when creating new packages. Mouse over each line to discover more about
the configuration items.
Let’s have a closer look at the configuration we have created for the X-Men package.

1
http://getcomposer.org/
2
http://composer.json.jolicode.com/
Composer 31

Example 02: Package name.


1 {"name": "marvel/xmen"}

This is the package name. If you have used Github3 then the name format will be
familiar to you, but I’m going to explain it anyway.
The package name consists of two words separated by a forward slash (/). The part
before the forward slash represents the owner of the package. In most circumstances,
developers will use their Github username as the owner, and I fully agree with this
notion. You can, however, use any name you like. Be sure to keep it consistent across
all packages that belong to you.
The second part of the name string is the package name. Keep it straightforward
and descriptive. Many developers choose to use the repository name for the package
when hosted on Github, and once again I fully agree with this system.

Example 03: Package description.


1 {"description": "Mutants saving the world for people who hate them."}

Provide a brief description of the functionality of the package. Remember to keep it


simple. If the package is intended for open source, then you can go into detail within
the README file for your repository. If you want to keep some personal documentation,
then this isn’t the place for it. Maybe get it tattooed on your back and keep a mirror
handy? That makes the most sense to me. Sticky notes will also work well, though.

Example 04: Keywords.


1 {"keywords": ["mutant", "superhero", "bald", "guy"]}

These keywords are an array of strings used to represent your package. They are
similar to tags within a blogging platform and essentially serve the same purpose.
The tags will provide useful search metadata for when your package is listed within a
repository.

Example 05: Homepage.


1 {"homepage": "http://marvel.com/xmen"}

The homepage configuration is useful for packages due to be open-sourced. You


could use the homepage for the project, or maybe the Github repository URL?
Whichever you feel is more informative.
Once again, I must remind you that all of these configuration options are optional.
Feel free to omit them if they don’t make sense for your package.
3
http://github.com
Composer 32

Example 06: Release date.

1 {"time": "1963-09-01"}

This is one of those options that I don’t see very often. According to the cheat sheet,
it represents the release date of your application or library. I’d imagine that it’s not
required in most circumstances because most packages are hosted on Github or some
other version control site. These sites normally date each commit, each tag, and other
useful events.
Formats accepted for the time configuration are YYYY-MM-DD and YYYY-MM-DD HH:MM:SS.
Go ahead and provide these values if you feel like it!

Example 07: License information.

1 {"license": "MIT"}

If your package is due to be redistributed, then you will want to provide a license
with it. Without a license, many developers will not be able to use the package at all
due to legal restrictions. Choose a license that suits your requirements, but isn’t too
restrictive to those hoping to use your code. The Laravel project uses the MIT license
which offers lots of freedom.
Most licenses require you to keep a copy of the license within the source repository,
but if you also provide this configuration entry within the composer.json file then the
package repository will be able to list the package by its license.
The authors section of the configuration provides information about the package
authors and can be useful for package users wishing to make contact.
Note that the authors section will allow an array of authors for collaborative packages.
Let’s have a look at the options given.

Example 08: The author object.

1 {
2 "authors": [
3 {
4 "name": "Stan Lee",
5 "email": "[email protected]",
6 "homepage": "http://marvel.com",
7 "role": "Genius"
8 }
9 ]
10 }
Composer 33

Use an object to represent each author. Our example only has one author. Let’s take
a look at Stan Lee. Not only does he have a cameo in every Marvel movie, but he’s also
managed to make it into my book. What a cheeky old sausage!

Example 09: Author name.

1 {"name": "Stan Lee"}

I don’t know how to simplify this line. If you are having trouble understanding it, then
you might want to consider closing this book, and instead pursue a career in sock
puppetry.

Example 10: Author email.

1 {"email": "[email protected]"}

Be sure to provide a valid email address so that you can be contacted if the package
is broken.

Example 11: Author homepage.

1 {"homepage": "http://marvel.com"}

This time, a personal homepage can be provided, go ahead and leech some hits!

Example 12: Author role.

1 {"role": "Genius"}

The role option defines the author’s role within the project. For example, developer,
designer, or even sock puppetry artist. If you can’t think of something accurate, then
put something funny.
That’s all you need to describe your package. Let’s look at something more interesting.
Dependency management!

Dependency Management
You have a box that will contain the X-Men. There aren’t a lot of mutants in that box
yet, are there? To build a great superhero team (application) you will need to enlist the
support of other mutants (3rd party dependencies). Let’s take a look at how Composer
will help us accomplish this.
Composer 34

Example 13: The require block.

1 {
2 "name": "marvel/xmen",
3 "description": "Mutants saving the world for people who hate them.",
4 "keywords": ["mutant", "superhero", "bald", "guy"],
5 "homepage": "http://marvel.com/xmen",
6 "time": "1963-09-01",
7 "license": "MIT",
8 "authors": [
9 {
10 "name": "Stan Lee",
11 "email": "[email protected]",
12 "homepage": "http://marvel.com",
13 "role": "Genius"
14 }
15 ],
16 "require": {
17
18 }
19 }

We now have a new section within our composer.json called ‘require’. This will be
used to list our dependenc… mutants. From now on I’ll be omitting the rest of the
configuration, and just showing the require block to shorten the examples. Make sure
you know where it lives!
We know that the X-Men will depend on:

• Wolverine
• Cyclops
• Storm
• Gambit

There are loads of others, but these guys are cool. We will stick with them for now.
You see, we could copy the source files for these guys into our application directly,
but then we would have to update them ourselves with any upstream changes. That
could get boring. Let’s add them to the require section so that Composer will manage
them for us.
Exploring the Variety of Random
Documents with Different Content
The Project Gutenberg eBook of Piccole storie
del mondo grande
This ebook is for the use of anyone anywhere in the United
States and most other parts of the world at no cost and with
almost no restrictions whatsoever. You may copy it, give it away
or re-use it under the terms of the Project Gutenberg License
included with this ebook or online at www.gutenberg.org. If you
are not located in the United States, you will have to check the
laws of the country where you are located before using this
eBook.

Title: Piccole storie del mondo grande

Author: Alfredo Panzini

Release date: November 10, 2012 [eBook #41342]


Most recently updated: October 23, 2024

Language: Italian

Credits: Produced by Carlo Traverso, Claudio Paganelli, Barbara


Magni and the Online Distributed Proofreading Team at
http://www.pgdp.net (This file was produced from
images
generously made available by The Internet Archive)

*** START OF THE PROJECT GUTENBERG EBOOK PICCOLE STORIE


DEL MONDO GRANDE ***
Alfredo Panzini

Piccole Storie
del
Mondo Grande

LEUMA E LIA
IL CUORE DEL PASSERO
LE OSTRICHE DI SAN DAMIANO
NELLA TERRA DEI SANTI E DEI POETI
LE VICENDE DEL SIGNOR X*** E DELLA SIGNORINA Y***
I TRE CASI DEL SIGNOR AVVOCATO
LA BICICLETTA DI NINÌ
IL PRIMO VIAGGIO D'AMORE
IL CINABRO RIVELATORE
LE VIOLE

MILANO
Fratelli Treves, Editori

13.º migliaio.
PROPRIETÀ LETTERARIA.
I diritti di riproduzione e di traduzione sono riservati per tutti i paesi,
compresi la Svezia, la Norvegia e l'Olanda.
Milano, Tip. Treves — 1920.
INDICE.
Dedicatoria Pag. v
Leuma e Lia 1
Il cuore del passero 75
Le ostriche di San Damiano 93
Nella terra dei santi e dei poeti 111
Le vicende del signor X*** e della signorina
Y*** 195
I tre casi del signor avvocato 221
La bicicletta di Ninì 255
Il primo viaggio d'amore 285
Il cinabro rivelatore 313
Le viole 333
DEDICATORIA

ALLA MIA CARA MAMMA


Filomena Santini vedova Panzini.

Queste novelle, mia cara mamma, siano dedicate a te, anche perchè
un poco di merito ce l'hai tu.
Non che tu le abbia emendate o mi abbia incoraggiato a scrivere:
anzi!
Ti ricordi? Le mattine d'estate, quando suonava la campanella, tu
piano piano uscivi dalla tua stanza — i cari bambini dormivano
ancora o sognavano la spiaggia del nostro bel mare — con lo scialle
nero in testa e il libro della messa: alzavi il saliscendi della porta
della mia stanza e mi trovavi già curvo su le carte e sui libri. Tu
dicevi: “Guarda che bel sole (e il sole, sorto da poco, filtrava dalle
persiane verdi), monta in bicicletta, va a fare una bella passeggiata,
invece di star lì a ammuffire tutto il santo giorno„, e te ne andavi
scuotendo il capo con mestizia e commiserazione.
Nè devi ancora esserti dimenticata che qualche mio scritto fece
inavvertitamente, per opera tua, conoscenza con le fiamme del
focolare. Allora te ne rimproverai, ma oggi...! oggi, chissà? Forse,
meglio: alle fiamme purificatrici i fantasmi della passione e del
pensiero: nel mondo e fra gli uomini le sane e forti opere. Certo tu
non pensavi, ma intuivi così, cara mamma!
Anche per quello che riguarda l'arte non ebbi da te troppi
ammaestramenti. Tu, in fatto di romanzi e di letture, sei rimasta,
caso mai, fedele alla vecchia scuola: cioè i gran romanzi, in uso molti
anni fa, pieni di avventure che ti conciliano piacevolmente il sonno
dopo il desinare del mezzodì. Quanto al pane dell'anima, sei
contenta delle semplici parole di Cristo che sono ne' tuoi breviari, da
te postillati con parole buone di speranza, di perdono e d'amore. La
nuova arte che scruta sottilmente le passioni e le tempeste dei
mortali, è passata vicina alla tua ignoranza: e tu non ti sei accorta di
queste superbe conquiste dell'ingegno.
Dunque non grande conforto, come vedi, io ebbi da te a questi miei
studi e a queste tormentose e pure affascinanti fatiche dell'imaginare
e dello scrivere.
Però se tu, cara, avrai la pazienza di scorrere queste belle pagine —
belle per la onorata veste dell'arte tipografica — vi troverai qualche
cosa di te, e capirai perchè a te le volli dedicate.
Queste novelle — ancor che umile frutto di quella passione e di
quella nobile malattia del pensiero che spesso distrugge la vita
scorza a scorza — non sono opposte a quei principi umani a cui è
stata conformata la tua vita. Vi troverai l'amore e la venerazione per
le cose e per le opere semplici e generose: vi troverai anteposta la
coscienza e la verità alla fortuna e il disdegno di ogni proficua viltà;
e questo è avvenuto non per alcun merito mio o per deliberato
proposito di far opera morale (tanto più che la morale, proseguita da
sola, ha in arte un ben tenue valore: inoltre — affermano i savi
moderni — la morale è fenomeno mutevole di sentire secondo il
mutare della società e della storia), ma perchè tali principi mi furono
da te inspirati, e in questa maniera di sentire e di operare tu, benchè
non dotta di filosofia e di lettere, mi fosti naturale maestra del pari
che il Maestro mio venerato e grande di Bologna (tu ne conosci il
caro nome, spesso ripetuto sotto il nostro umile tetto!).
Certo con tali principî la conquista materiale della fortuna non è stata
agevole, anzi...! e non lo sarà, a quel che pare, nè meno per
l'avvenire!
Vero è che non sarai tu a farmene rimprovero.
Ma il sole splende su tutti e non fa pagare i suoi raggi, e poca terra
ricoprirà noi come i conquistatori della fortuna e della vita!
Troverai anche in queste novelle accenni a care persone che più non
sono e che molto amammo e che tu nutri fede di rivedere.
Per queste ragioni accetta l'offerta di questo libro e vivi a lungo sana
e consolata per mio conforto.
Milano, ne l'aprile del 1901.
Alfredo Panzini.
LEUMA E LIA.

Da sette anni l'onorevole Astese non vedeva il dottor Leuma, anzi —


a rigor di termini — non sapeva nè pur più dove fosse: se in questa
vita o nell'altra.
Ma secondo ogni verosimiglianza dovea essere in questo mondo
perchè non fu mai detto che i dottori muoiano come una persona
qualsiasi.
Ora è certo che l'onorevole Astese, se avesse avuto a pena una
settimana libera, si sarebbe messo subito alla ricerca di quel caro
compagno di Leuma. Oh, lo avrebbe sì ripescato e avrebbe con lui
rinnovato alcuna cosa della giovinezza, oimè, della giovinezza così da
poco tempo fuggita e pure già così lontana. Oh, potersi riposare
all'ombra o al sole con Leuma e provare il gran piacere di dire delle
sciocchezze senza la paura di perdere di gravità, e portare anche i
mattoni a quelle gran fabbriche di castelli in aria di cui Leuma era
maestro architetto! Ma, oimè, se Leuma era vivo, li sapeva ancor
fare i bei castelli, cioè era ancora viva la sua giovinezza del cuore; o
era morta come era morta in lui?
Morta in lui? Che ne sapeva mai lui, Astese? Quando mai egli aveva
avuto tempo di fare queste profonde analisi di se stesso?
Ma della giovinezza di Leuma si ricordava bene!
Erano stati compagni di collegio a Venezia per alcuni anni: egli era
fra i grandi e Leuma fra i piccini; un pallido, meditabondo giovanetto
con una grande anima che si apriva allora piena di sussulti in un
esile corpo; ed egli, Astese, ne riceveva le prime confidenze, e lo
amava con quella idealità e pur non so quale tenerezza di sensi
come spesso avviene in collegio, e lo difendeva dalla protervia de'
compagni. Poi lo ricordava per alcun tempo, fuor del collegio,
ventenne, bellissimo. Come si era trasfigurato con la libertà! Ebbro di
entusiasmi, con i capelli lunghi, i fiori su la bottoniera, nitrente verso
l'avvenire come un puledro. “Signori, — pareva dire — Venezia è da
vendere? Il mondo va male? lo trasformerò io: I segreti della gloria e
della fortuna sono nel taschino del mio gilè.„
E poi?
Scomparso!

*
Astese non aveva mai avuto nessuno dei fremiti e dei sogni di
Leuma, anzi si divertiva a contemplarne lo spettacolo in Leuma:
talvolta anche si aggrappava, per così dire, alle gambe di lui; ma a
pena si sentiva un po' lontano da terra, lo pregava di tornar giù e
fare il piacere di mettere il piede sul sodo.
Eppure a trentasei anni Astese si era fatta — si può dire dal nulla e
senza sforzi eccezionali — una posizione invidiabile: avvocato quasi
celebre, pubblicista autorevole, in fine, deputato.
Anche io come molti altri mi sono chiesto in che mai consistesse il
segreto di tanta fortuna, e non ci sono riuscito. Se lo sapessi dire,
come diventerebbe prezioso questo mio libro, e come ne
approfitterei io stesso! No, non lo so dire. Ecco: forse ne' suoi
occhiali d'oro che ridevano sempre su lo scarno e arguto suo volto
sbarbato, e parevano dire: “Noi, dopo aver bene esaminato, pigliamo
il mondo sul serio per quel tanto che basta a non diventare scettici o
filosofi pessimisti.„
In pretorio, quando cominciava a parlare, diventavano di buon
umore anche i giudici: eppure Astese non era un farceur!
Nell'ultima battaglia elettorale glie ne scrissero e dissero d'ogni
colore gli avversari: una sola dimenticarono, cioè questa: “Signore,
siete antipatico!„ Eppure Astese col suo naso, col suo collo ricordava
lontanamente il cammello.
Astese non era un artista e non era un uomo di genio: eppure i suoi
articoli erano letti e citati.
Sì, è vero: vi sono piccole qualità preziose: un motore minuscolo
produce di più che tutto l'impeto di un uragano. Esistono nel mondo
morale, come nel mondo fisico, gli infinitamente piccoli da cui si
genera la fortuna nel commercio della vita.
E la potenza di adattamento all'ambiente non la si conta?
Ah, sì! Quando la scienza ci avrà fornito il mezzo per apprendere la
forza di adattamento, noi almeno, poveri inseguitori di farfalle e di
ideali, impareremo di gran cose!

*
— Ah, onorevole, come dovete essere felice voi! senza moglie, senza
figli, senza fastidi: un mondo di quattrini: un portafogli in
prospettiva! — sospiravano gli amici.
— Taci, — rispondeva Astese in tuono lugubre. — Sai tu cosa v'è qui
dentro?

io mi sento simile al saltambanco


che muor di fame, e in vista ilare e franco
trattien la folla.

“Io allegro, io felice, io? — ripeteva poi talvolta a se stesso, specie


nel silenzio mattutino della sua stanza. — Felice tu, miserabile?„ e si
appuntava con volto tragico il dito contro la specchiera: ma poi gli
veniva da ridere, guardandosi. “Va là, mato anca tì!„ concludeva
vestendosi in fretta e facendosi “ciao„ nel suo inestinguibile dialetto
veneto.

*
— In prima non c'è più posto, onorevole.... Le carrozze sono tutte
occupate da una compagnia di americani che vanno a Roma a
vedere il Papa....
— Allora favorisca dirmi dove posso montare....
— Se crede, faccio attaccare una carrozza, onorevole.... — gli
andava dicendo dietro il capostazione.
— Manco per sogno: monto in seconda....
E il capostazione stesso gli aperse uno sportello di seconda classe
con un: — qui, passi qui: c'è posto; — e sospinse su l'onorevole
Astese, che era proprio lui ed era assai impicciato perchè avea il
plaid, la sacca da viaggio, il portafoglio curiale, il bastone, l'ombrello,
la spolverina e la testa fuori di posto che è il peggio bagaglio. Era
stato chiamato a Modena per una grossa causa di fallimento. Era
giunto al mattino: avea perorato, avea quasi vinto. Avrebbe così
potuto dire come Cesare: veni vidi vici: cosa che ad Astese accadeva
di frequente. Questa volta interruppe la vittoria un telegramma del
Presidente del Consiglio che lo chiamava d'urgenza a Roma per il
voto di fiducia.
— Parto, ma giuro, signori, — diceva ferocemente ai clienti che ritti
sull'andana lo ossequiavano, — giuro che fra tre giorni, al mio
ritorno, se non pagano, porteremo via anche i chiodi. Cosa? Non ci
sono i danari? Oh, li faremo venir fuori noi....!
Lo schianto del treno, partendo, lo fece cader giù sul divano. Poco
dopo, i chiodi, la ferocia, la causa fuggivano via dal finestrino
insieme al fumo della sigaretta. Queste gravose cose egli dava ad
intendere che le portava seco; ma nel fatto le lasciava presso i
clienti.
Quando i vapori della concitazione avvocatesca cominciarono a
dissiparsi, vide uno che lo guardava come se lo volesse conoscere.
Diede un gran salto e gridò:
— Tu sei Leuma, tu sei!
— Tu sei Astese, — disse un bel signore giovane, il quale aveva
un'elegante barba nera e quadrata. Ma nel dire queste parole le gote
arrossirono e gli occhi, assai dolci, presero un'espressione di
imbarazzo e quasi di timidezza: rossori e timidezze che quella barba
virile avea la missione di nascondere.
Ma Astese non se ne accorse: gli si buttò a dosso, lo baciò con certe
espressioni d'amore, famigliari su le lagune di Venezia, che gli erano
rimaste in fondo della memoria dal tempo del collegio; le quali se
convenivano a Leuma, quando era adolescente, disdicevano a Leuma
con quella barba nera.
Leuma sorrise e si vedeva che cercava di parlare anche lui a pena
fosse cessata la tempesta delle domande e delle carezze.
Allora un sottile scoppio di risa si udì, benchè fosse assai sottile e
come represso, il quale però ebbe la virtù di fermare le parole di
Astese e fargli volgere gli occhi dalla parte da cui veniva quel riso
motteggiatore. Gli occhi di Astese si incontrarono in due altri occhi
incantati su di lui come su di un saltimbanco, ed appartenevano al
volto di una giovanetta di fine e commovente bellezza.
I quattro occhi si fissarono per un istante, e quelli dell'onorevole
Astese si sarebbero certamente corrucciati e le parole avrebbero
detto: “Signorina, lei è un'impertinente!„ ma quegli occhi
esprimevano una meraviglia così pura e quel volto era così
adorabilmente giovane, che Astese non increspò il sopracciglio nè
disse parola.
La signorina capì nondimeno d'aver fatto male, si voltò subito dalla
parte del finestrino e pareva molto confusa: e un signore di mezza
età che le sedeva di fronte, le battè su le ginocchia e fece segno col
capo, come a dire: “Via, così non sta bene!„
Leuma approfittò del silenzio per dire: — Amico mio, noi siamo
arrivati oramai.... È un peccato doverci lasciare....
— Arrivato? lasciarci? ma nè pur per sogno, — disse Astese.
— Ma io non posso proseguire, — disse Leuma con imbarazzo.
— Ma mi fermo io, tesoro. Il Ministero farà a meno del mio voto: non
sarò certo io quello che terrà su la baracca....
— Già, tu sei deputato.... non ci pensavo nè meno più, — disse
Leuma; e lo disse timidamente, come se questo pensiero lo ponesse
in condizione di evidente inferiorità.
— Ma perchè se sapevi che io ero deputato e tante altre cose di me,
non mi hai mai scritto? e io che ti cercavo per mare e per terra!
— Perchè? — rispose Leuma con non so quale amarezza — perchè io
sono rimasto troppo ignoto.... Tu invece....
Il treno intanto frenò di botto: ed egli, Astese, raccoglieva le sue
cose, che urtate e mal prese, balzavano dai sedili come malvagi
spiritelli.
Scesero che ne ebbero a pena il tempo, e il treno avea ripreso la sua
corsa verso le tenebre che velavano oramai l'emisperio d'oriente,
mentre l'occidente si incendiava al passaggio del sole. Era una
piccola stazione perduta nella pianura, e quando si spense il fragore
del treno, ben si sentì il canto dei grilli e si sentì odore del trifoglio
falciato, il quale metteva nell'aria un'indistinta frigidezza di verde e di
viole.
Allora Leuma, levando il braccio, disse sorridendo:
— Io ti presento, Astese, mia moglie e il mio buon suocero: non l'ho
fatto prima perchè tu me ne hai tolto il tempo; — e indicava ad
Astese il signore e la signorina che erano nel treno e che pur essi
erano discesi, nè Astese vi avea posto mente. — E questi è il mio
amico, l'onorevole Vittorio Astese, di cui vi ho parlato tante volte; —
proseguì quando Astese si fu levato dal profondo inchino che per la
sorpresa gli avea fatto cadere gli occhiali dal naso; un naso sottile e
gibboso che gli tagliava il volto olivigno: un naso dove gli occhiali
aveano una base resistente a tutte le scosse oratorie. E pur questa
volta erano caduti.
A quel residuo di vanità che rimaneva ad Astese a dispetto della sua
grande saviezza, parve che la signorina, o per dir più propriamente,
la signora rimanesse a bastanza indifferente davanti all'onorevole
personaggio; ma guardava ogni tanto verso un viale di alti pioppi dal
cui fondo ora spuntava una timonella e si udiva la sonagliera del
cavallo.
Quando arrivò la timonella, caricarono le valigie, presero posto e si
avviarono di bel trotto pel lungo viale ove i raggi del tramonto
traversando l'una spalliera dei pioppi, saettavano l'altra di languide
frecce.
Astese, seduto davanti alla sposina, si era acquetato e pareva come
assorto nella strana combinazione che lo metteva di fronte a quel
volto infantile, invece di trottare verso Roma per recare aiuto al
cadente Ministero. Ma ecco si scoprì la facciata di una villetta.
Davanti al cancello v'era una signora con una fantesca che avea un
bambino in braccio: il bambino, appena vide la carrozza, cominciò a
alzar le mani, e subito la sposina spiccò un salto dalla carrozza giù
verso il piccino senza badar a nessuno. “Ocio, che la no casca!„ le
disse dietro l'onorevole Astese, spaventato a quel salto mentre la
carrozza era ancora in moto. La signora, che era la suocera, accolse
l'amico di Leuma con belle parole e con quell'accento emiliano pieno
di umili inflessioni che hanno sol di per sè un suono di natia
gentilezza italiana. Ella non d'altro si meravigliò se non che Astese
fosse deputato, giacchè i deputati se li imaginava mica giovani e
neanche così alla buona.
— Ma scusa, — disse finalmente Astese fermando Leuma per un
braccio, quando furono saliti al primo piano nella stanza ospitale
destinata all'amico, — anche quel bambino è proprio tuo?
— Sì....
— Ma quant'è che hai preso moglie?
— Quasi due anni fa.
— E la tua signora quanti anni ha?
— Oramai diciannove.
— Ma se la xe una putela....
— Te lo dirò poi, — disse Leuma sorridendo, — ora fa il comodo tuo;
— e posò un largo lume a petrolio, che cominciava ad annottare.
Era una stanzetta intatta con il soffitto a vôlta, dipinta d'azzurro,
secondo lo stile di un sessant'anni fa; proprio la stanza degli ospiti.
Astese guardò attorno i mobili dalle antiche sagome, disposti in
ordine e sgombri: parevano dire: “Sì, signore, proprio la stanza degli
ospiti.„ Spinse l'occhio fuori della finestra e vide molta pace e molto
silenzio intorno alla villa. Sotto vi dovea essere un giardino e si
distingueva un'ombra di donna e una voce che chiamava: “Pi, pi, pi!
a nanna!„ Saettarono alcune ombre, piccine, convergenti in un sol
punto; le galline che andavano a letto.
Frattanto in abbondante acqua cominciò a detergersi dai sudori della
concione e dalla polvere: alzò il ciuffo di una capigliatura sottile e
sfumata: adattò una cravattina bianca ad una camicia di batista, un
soprabito nero su la camicia, sì che avea preso un aspetto più
conforme all'alto suo grado.
E così sporgendo il ciuffo e il naso che sorreggeva le lanterne degli
occhietti vivaci, apparve nella sala da pranzo ove la famiglia era
raccolta sotto una bella lampada presso una tavola candida e fiorita
di bellissimi fiori. Leuma gli andò incontro e la sposa allora sorrise
vedendolo.
— Benedetta, che la ride finalmente! — disse Astese — non deve
mica aver paura di me; non glielo porto mica via il suo sposo! Ma sai
— e si rivolgeva a Leuma — che io ci pensavo a questo caso, cioè
che una delle tante fate di nostra anzi di tua conoscenza ti avesse
rapito e sottratto alle delusioni del mondo?
Il complimento ebbe la virtù di fare a pena sorridere Leuma, ma Lia
rimase seria. Allora Astese, accorgendosi che quel tasto rispondeva
poco bene, pensò di prendere in braccio il bambino, a cui rivolse
molte domande:
— Come stai? Vuoi bene al papà? La fai arrabbiare la mamma? Vuoi
fare l'avvocato quando sarai grande? Ih, come sei cattivo!
Il bambino aveva per un po' guardato quella faccia nuova, poi
scoppiò in un disperato pianto che sconcertò l'onorevole Astese.
— Dia, dia a me, onorevole, — disse la sposa ridendo, — perchè il
piccolo fagiolino le può rispondere con delle sorprese; lui non
distingue mica un onorevole dalla sua mamma, vero, cocco? — e se
lo prese sottraendo l'abito del signore da possibili guasti.
La signora suocera entrò sorreggendo trionfalmente fin su la tavola
una gran fiamminga, e disse:
— Minestra di tagliolini fatti in casa: roba alla buona, signor
deputato: favorisca la sua tondina.
Fuori delle finestre aperte c'erano gli alti pioppi che stavano a
vedere; e saettò allora dalla densa verzura un trillo di rosignolo che
salì, poi si franse e cadde come gemme in alabastro.
— Avete anche i rosignoli, avete?
— E le lucciole, — disse Lia; — vedrà quante: fra poco andranno
tutte a spasso per il grano.
Il pranzo fu rallegrato da squisite vivande dichiarate con breve chiosa
dalla signora suocera, e dalle più felici arguzie di Astese, tanto che il
signor suocero non si poteva in cuor suo persuadere che una
persona tanto per bene e cordiale fosse uno di que' signori che, a
suo giudizio, mandano a perdizione la patria.
E quando il pranzo fu finito, Astese, benchè la giovane sposa si
schermisse, volle sapere tutta la storia. Ma gli convenne molto
pregare e anche disse:
— Veda, sposina, questo mio povero amico di Leuma che da tanti
anni più non vedevo, io lo credevo perduto: ora invece lo ho
ritrovato e mi pare che abbia trovato anche la felicità.
E rivolto a lui, aggiunse con tuono lievemente patetico ed enfatico,
forse più per l'abuso dell'arte sua che per deliberato volere:
— Sotto la barba nera che ora ti ricopre il mento, io non riconosco
più il volto soave dell'adolescente che allora eri. Ma gli occhi sono
sempre gli stessi, e anche la bella parola. Ti ricordi che i compagni di
collegio ti burlavano perchè parlavi l'italiano? Ti ricordi nella corte
presso i sicomori fioriti che passeggiavi su e giù solitario, meditando
sui versi del Prati? e piangevi che volevi essere libero perchè ogni
notte le fate ti portavano un sogno e tu mi assicuravi che il tempo
fuggiva? E avevi quindici anni! Io ridevo. Ma avevi ragione tu, sai? Il
tempo fuggiva. Povero piccino; io ti amava allora e ti confortava; ma
tu adesso hai trovato un conforto ben maggiore e un affetto più
sicuro.
Così disse Astese, ed all'evocazione del ricordo antico Leuma sorrise
da vero melanconicamente e — Tristi tempi, in fondo — mormorò. —
Giovanezza tradita!... — Poi lambendo con la mano la testa della
sposa, proseguì: — Le cose che tu sei curioso di sapere, sono
semplici; il tuo amico che aveva mezzo mondo da conquistare e poco
tempo da perdere perchè la gloria e le fate, che tu hai ricordato
molto a proposito, gli dicevano di fare presto, il tuo amico si è
trovato un bel giorno nella necessità di conquistare la carica di
segretario comunale qui, in questo comune. Quanto poi al tempo, mi
era venuto tanto in uggia che l'avrei fermato volentieri come quando
si butta per terra un orologio che ci secca col suo tic-tac. Cos'hai
adesso? — e questa dimanda era rivolta a Lia.
— Niente: perchè parli così? — disse Lia che gli teneva stretta la
mano e lo spiava nel volto.
— Così per ridere, figliuola: così per spiegare a questo mio amico
come talvolta vanno le cose del mondo.
Del resto la concitazione e il sarcasmo nella voce di Leuma furono
una cosa tanto fuggevole che Astese non se ne sarebbe nè meno
accorto senza la interruzione di Lia.
— Dunque, — proseguì Leuma, — io divento segretario comunale
del paese. Allora qui avevamo un ginnasio, una di quelle tante
fabbriche di spostati che abbondano in Italia. Adesso, grazie al cielo,
lo abbiamo abolito.
— Il nostro Leuma, onorevole, — avvertì pianamente il suocero, — è
assessore....
— Puoi dire che è lui il sindaco.... — corresse la suocera.
— Via, via, — interruppe Leuma sorridendo, — finiamola con questa
storia: il sindaco è il conte Losti....
Il suocero si accontentò di alzare le spalle.
— Non ci creda, sa, onorevole, — disse la suocera, — il sindaco vero
è Leuma.
— Be', andiamo avanti: dunque ti dicevo che avevamo un ginnasio
con tre professori, professori così per dire, e una ventina di scolari in
tutto. Io era a pena in paese da sei mesi, quando mi vengono a
pregare di supplire il professore di quarta classe che avea preso il
volo per altri lidi. Un avvocato può supplire a tutto: io poi sapevo di
lettere, quindi ero indicatissimo come professore. Accettai. Vado a
scuola, e indovina un po' chi vedo fra i quattro scolari? Una certa
signorina, anzi una certa bambina che si chiamava a punto Lia....
— Così che tu hai sposato la tua scolara? — disse Astese.
— Proprio così.
— Adesso comincia il bello, conta, conta su.
— Cosa vuol contare? — disse Lia; — la storia è finita e il bambino
ha sonno: io ho sposato lui e lui ha sposato me.
— Ma i particolari, sposina. Ma scusi, la storia senza particolari non
val nulla.
— Il particolare più importante è questo: lui ha voluto bene a me e
io — disse ella arrossendo — ho voluto bene a lui, e adesso punto e
basta. Vero che hai sonno, piccino? vero che è la tua ora d'andare a
nanna?
Tutte le argomentazioni di Astese — e ognuno può pensare se ne
aveva a dovizia — non valsero a far sì che Lia desse il suo
acconsentimento di proseguire.
Welcome to our website – the perfect destination for book lovers and
knowledge seekers. We believe that every book holds a new world,
offering opportunities for learning, discovery, and personal growth.
That’s why we are dedicated to bringing you a diverse collection of
books, ranging from classic literature and specialized publications to
self-development guides and children's books.

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


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

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


personal growth every day!

ebookbell.com

You might also like