Laravel. Up and Running, 3rd Edition / Запускаем Laravel, 3-е издание Год издания: 2024 Автор: Stauffer Matt / Стаффер Мэтт Издательство: O’Reilly Media, Inc. ISBN: 978-1-098-15326-7 Язык: Английский Формат: PDF, EPUB Качество: Издательский макет или текст (eBook) Интерактивное оглавление: Да Количество страниц: 562 Описание: What sets Laravel apart from other PHP web frameworks? Speed and simplicity, for starters. This rapid application development framework and its ecosystem of tools let you quickly build new sites and applications with clean, readable code. Fully updated to include Laravel 10, the third edition of this practical guide provides the definitive introduction to one of today’s most popular web frameworks. Matt Stauffer, a leading teacher and developer in the Laravel community, delivers a high-level overview and concrete examples to help experienced PHP web developers get started with this framework right away. This updated edition covers the entirely new auth and frontend tooling and other first-party tools introduced since the second edition. Dive into features, including: Blade, Laravel’s powerful custom templating tool Tools for gathering, validating, normalizing, and filtering user-provided data The Eloquent ORM for working with application databases The Illuminate request object and its role in the application lifecycle PHPUnit, Mockery, and Dusk for testing your PHP code Tools for writing JSON and RESTful APIs Interfaces for filesystem access, sessions, cookies, caches, and search Tools for implementing queues, jobs, events, and WebSocket event publishing Specialty packages including Scout, Passport, Cashier, and more Что отличает Laravel от других веб-фреймворков на PHP? Прежде всего, скорость и простота. Этот фреймворк для быстрой разработки приложений и его экосистема инструментов позволяют быстро создавать новые сайты и приложения с чистым, читаемым кодом. Третье издание этого практического руководства, полностью обновленное и включающее Laravel 10, представляет собой исчерпывающее введение в один из самых популярных веб-фреймворков на сегодняшний день. Мэтт Стаффер, ведущий преподаватель и разработчик в сообществе Laravel, представляет обзор высокого уровня и конкретные примеры, которые помогут опытным веб-разработчикам PHP сразу же приступить к работе с этим фреймворком. В этом обновленном издании представлены совершенно новые средства аутентификации и интерфейса, а также другие сторонние инструменты, появившиеся после выхода второго издания. Ознакомьтесь с функциями, включая: Blade, мощный инструмент для создания пользовательских шаблонов в Laravel Инструменты для сбора, проверки, нормализации и фильтрации предоставленных пользователем данных Модуль Eloquent ORM для работы с базами данных приложений Объект запроса Illuminate и его роль в жизненном цикле приложения PHPUnit, Mockery и Dusk для тестирования вашего PHP-кода Инструменты для написания JSON и RESTful API Интерфейсы для доступа к файловой системе, сеансов, файлов cookie, кэшей и поиска Инструменты для создания очередей, заданий, событий и публикации событий в WebSocket Специальные пакеты, включая Scout, Passport, Cashier и другие
Примеры страниц (скриншоты)
Оглавление
Preface xix 1. Why Laravel? 1 Why Use a Framework? 1 “I’ll Just Build It Myself ” 2 Consistency and Flexibility 2 A Short History of Web and PHP Frameworks 2 Ruby on Rails 2 The Influx of PHP Frameworks 3 The Good and the Bad of CodeIgniter 3 Laravel 1, 2, and 3 3 Laravel 4 4 Laravel 5 4 Laravel 6 4 Laravel Versions in the New SemVer World (6+) 5 What’s So Special About Laravel? 5 The Philosophy of Laravel 5 How Laravel Achieves Developer Happiness 6 The Laravel Community 7 How It Works 7 Why Laravel? 10 2. Setting Up a Laravel Development Environment. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11 System Requirements 11 Composer 12 Local Development Environments 12 Artisan Serve 12 Laravel Sail 12 Laravel Valet 13 Laravel Herd 13 Laravel Homestead 13 Creating a New Laravel Project 14 Installing Laravel with the Laravel Installer Tool 14 Installing Laravel with Composer’s create-project Feature 14 Installing Laravel with Sail 14 Laravel’s Directory Structure 15 The Folders 15 The Loose Files 16 Configuration 17 The .env File 18 Up and Running 20 Testing 21 TL;DR 21 3. Routing and Controllers. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23 A Quick Introduction to MVC, the HTTP Verbs, and REST 23 What Is MVC? 23 The HTTP Verbs 24 What Is REST? 25 Route Definitions 26 Route Verbs 27 Route Handling 28 Route Parameters 29 Route Names 31 Route Groups 33 Middleware 34 Path Prefixes 35 Subdomain Routing 35 Name Prefixes 36 Route Group Controllers 37 Fallback Routes 37 Signed Routes 37 Signing a Route 38 Modifying Routes to Allow Signed Links 38 Views 39 Returning Simple Routes Directly with Route::view() 40 Using View Composers to Share Variables with Every View 40 Controllers 40 Getting User Input 43 Injecting Dependencies into Controllers 44 Resource Controllers 45 API Resource Controllers 47 Single Action Controllers 47 Route Model Binding 48 Implicit Route Model Binding 48 Custom Route Model Binding 50 Route Caching 50 Form Method Spoofing 51 HTTP Verbs in Laravel 51 HTTP Method Spoofing in HTML Forms 51 CSRF Protection 52 Redirects 53 redirect()->to() 54 redirect()->route() 54 redirect()->back() 55 Other Redirect Methods 55 redirect()->with() 56 Aborting the Request 58 Custom Responses 58 response()->make() 58 response()->json() and ->jsonp() 58 response()->download(), ->streamDownload(), and ->file() 59 Testing 59 TL;DR 60 4. Blade Templating. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 61 Echoing Data 62 Control Structures 63 Conditionals 63 Loops 64 Template Inheritance 66 Defining Sections with @section/@show and @yield 66 Including View Partials 68 Using Components 70 Using Stacks 74 View Composers and Service Injection 75 Binding Data to Views Using View Composers 76 Blade Service Injection 79 Custom Blade Directives 80 Parameters in Custom Blade Directives 81 Example: Using Custom Blade Directives for a Multitenant App 81 Easier Custom Directives for “if ” Statements 82 Testing 83 TL;DR 84 5. Databases and Eloquent. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 85 Configuration 85 Database Connections 86 URL Configurations 87 Other Database Configuration Options 88 Migrations 88 Defining Migrations 88 Running Migrations 98 Inspecting Your Database 99 Seeding 99 Creating a Seeder 99 Model Factories 100 Query Builder 108 Basic Usage of the DB Facade 108 Raw SQL 109 Chaining with the Query Builder 110 Transactions 120 Introduction to Eloquent 121 Creating and Defining Eloquent Models 122 Retrieving Data with Eloquent 124 Inserts and Updates with Eloquent 126 Deleting with Eloquent 129 Scopes 132 Customizing Field Interactions with Accessors, Mutators, and Attribute Casting 135 Eloquent Collections 139 Eloquent Serialization 142 Eloquent Relationships 144 Eloquent Events 160 Testing 161 TL;DR 163 6. Frontend Components. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 165 Laravel Starter Kits 165 Laravel Breeze 166 Laravel Jetstream 167 Laravel’s Vite Configuration 169 Bundling Files with Vite 171 The Vite Dev Server 171 Working with Static Assets and Vite 172 Working with JavaScript Frameworks and Vite 173 Using Environment Variables in Vite 174 Pagination 175 Paginating Database Results 175 Manually Creating Paginators 177 Message Bags 178 String Helpers, Pluralization, and Localization 179 The String Helpers and Pluralization 180 Localization 181 Testing 185 Testing Message and Error Bags 185 Translation and Localization 185 Disabling Vite in Testing 185 TL;DR 186 7. Collecting and Handling User Data. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 187 Injecting a Request Object 187 $request->all() 188 $request->except() and ->only() 188 $request->has() and ->missing() 189 $request->whenHas() 189 $request->filled() 190 $request->whenFilled() 190 $request->mergeIfMissing() 190 $request->input() 191 $request->method() and ->isMethod() 191 $request->integer(), ->float(), ->string(), and ->enum() 191 $request->dump() and ->dd() 192 Array Input 192 JSON Input (and $request->json()) 193 Route Data 194 From Request 194 From Route Parameters 195 Uploaded Files 195 Validation 197 validate() on the Request Object 198 More on Laravel’s Validation Rules 199 Manual Validation 200 Using Validated Data 200 Custom Rule Objects 201 Displaying Validation Error Messages 202 Form Requests 202 Creating a Form Request 203 Using a Form Request 204 Eloquent Model Mass Assignment 204 {{ Versus {!! 206 Testing 206 TL;DR 207 8. Artisan and Tinker. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 209 An Introduction to Artisan 209 Basic Artisan Commands 210 Options 211 The Grouped Commands 212 Writing Custom Artisan Commands 214 A Sample Command 215 Arguments and Options 216 Using Input 218 Prompts 220 Output 221 Writing Closure-Based Commands 222 Calling Artisan Commands in Normal Code 223 Tinker 224 Laravel Dump Server 225 Customizing Generator Stubs 226 Testing 226 TL;DR 227 9. User Authentication and Authorization. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 229 The User Model and Migration 229 Using the auth() Global Helper and the Auth Facade 233 routes/auth.php, Auth Controllers, and Auth Actions 233 Breeze and Jetstream’s Frontend Templates 235 “Remember Me” 235 Password Confirmation 236 Manually Authenticating Users 236 Manually Logging Out a User 237 Invalidating Sessions on Other Devices 237 Auth Middleware 237 Email Verification 239 Blade Authentication Directives 239 Guards 240 Changing the Default Guard 240 Using Other Guards Without Changing the Default 241 Adding a New Guard 241 Closure Request Guards 241 Creating a Custom User Provider 242 Custom User Providers for Nonrelational Databases 243 Auth Events 243 Authorization and Roles 244 Defining Authorization Rules 244 The Gate Facade (and Injecting Gate) 245 Resource Gates 246 The Authorize Middleware 246 Controller Authorization 247 Checking the User Instance 249 Blade Checks 249 Intercepting Checks 250 Policies 250 Testing 253 TL;DR 255 10. Requests, Responses, and Middleware. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 257 Laravel’s Request Lifecycle 257 Bootstrapping the Application 258 Service Providers 259 The Request Object 260 Getting a Request Object in Laravel 261 Getting Basic Information About a Request 262 The Response Object 266 Using and Creating Response Objects in Controllers 266 Specialized Response Types 267 Laravel and Middleware 273 An Introduction to Middleware 273 Creating Custom Middleware 274 Binding Middleware 276 Passing Parameters to Middleware 279 Default Middleware 280 Maintenance Mode 280 Rate Limiting 280 Trusted Proxies 281 CORS 282 Testing 282 TL;DR 283 11. The Container. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 285 A Quick Introduction to Dependency Injection 285 Dependency Injection and Laravel 287 The app() Global Helper 287 How the Container Is Wired 288 Binding Classes to the Container 289 Binding to a Closure 289 Binding to Singletons, Aliases, and Instances 290 Binding a Concrete Instance to an Interface 291 Contextual Binding 292 Constructor Injection in Laravel Framework Files 293 Method Injection 293 Facades and the Container 295 How Facades Work 295 Real-Time Facades 297 Service Providers 297 Testing 298 TL;DR 299 12. Testing. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 301 Testing Basics 302 Naming Tests 305 The Testing Environment 306 The Testing Traits 307 RefreshDatabase 307 DatabaseMigrations 307 DatabaseTransactions 308 WithoutMiddleware 308 Simple Unit Tests 308 Application Testing: How It Works 309 HTTP Tests 310 Testing Basic Pages with $this->get() and Other HTTP Calls 310 Testing JSON APIs with $this->getJson() and Other JSON HTTP Calls 311 Assertions Against $response 312 Authenticating Responses 315 A Few Other Customizations to Your HTTP Tests 316 Handling Exceptions in Application Tests 316 Debugging Responses 317 Database Tests 317 Asserting Against the Database 318 Asserting Against Eloquent Models 318 Using Model Factories in Tests 319 Seeding in Tests 319 Testing Other Laravel Systems 319 Event Fakes 319 Bus and Queue Fakes 321 Mail Fakes 322 Notification Fakes 323 Storage Fakes 324 Working with Time in Tests 325 Mocking 326 A Quick Introduction to Mocking 326 A Quick Introduction to Mockery 326 Faking Other Facades 329 Testing Artisan Commands 330 Parallel Testing 332 Browser Tests 332 Choosing a Tool 332 Testing with Dusk 332 Pest 344 TL;DR 344 13. Writing APIs. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 345 The Basics of REST-Like JSON APIs 345 Controller Organization and JSON Returns 347 Reading and Sending Headers 350 Sending Response Headers in Laravel 351 Reading Request Headers in Laravel 351 Eloquent Pagination 351 Sorting and Filtering 353 Sorting Your API Results 354 Filtering Your API Results 355 Transforming Results 356 API Resources 357 Creating a Resource Class 357 Resource Collections 358 Nesting Relationships 360 Using Pagination with API Resources 361 Conditionally Applying Attributes 362 More Customizations for API Resources 363 API Authentication 363 API Authentication with Sanctum 363 API Authentication with Laravel Passport 367 Customizing 404 Responses 379 Triggering the Fallback Route 379 Testing 380 Testing Passport 380 TL;DR 381 14. Storage and Retrieval. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 383 Local and Cloud File Managers 383 Configuring File Access 383 Using the Storage Facade 385 Adding Additional Flysystem Providers 387 Basic File Uploads and Manipulation 387 Simple File Downloads 389 Sessions 389 Accessing the Session 389 Methods Available on Session Instances 390 Flash Session Storage 392 Cache 392 Accessing the Cache 393 Methods Available on Cache Instances 393 Cookies 395 Cookies in Laravel 395 Accessing the Cookie Tools 395 Logging 398 When and Why to Use Logs 399 Writing to the Logs 399 Log Channels 400 Full-Text Search with Laravel Scout 402 Installing Scout 403 Marking Your Model for Indexing 403 Searching Your Index 403 Queues and Scout 404 Performing Operations Without Indexing 404 Conditionally Indexing Models 404 Manually Triggering Indexing via Code 404 Manually Triggering Indexing via the CLI 405 The HTTP Client 405 Using the HTTP Facade 405 Handling Errors and Timeouts and Checking Statuses 406 Testing 407 File Storage 407 Session 409 Cache 410 Cookies 410 Log 411 Scout 412 HTTP Client 412 TL;DR 413 15. Mail and Notifications. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 415 Mail 415 Basic “Mailable” Mail Usage 416 Mail Templates 419 Methods Available in envelope() 420 Attaching Files and Inlining Images 421 Markdown Mailables 423 Rendering Mailables to the Browser 425 Queues 426 Local Development 426 Notifications 428 Defining the via() Method for Your Notifiables 430 Sending Notifications 431 Queueing Notifications 432 Out-of-the-Box Notification Types 432 Testing 436 Mail 436 Notifications 438 TL;DR 439 16. Queues, Jobs, Events, Broadcasting, and the Scheduler. . . . . . . . . . . . . . . . . . . . . . . . . 441 Queues 441 Why Queues? 442 Basic Queue Configuration 442 Queued Jobs 443 Running a Queue Worker 449 Handling Errors 449 Controlling the Queue 454 Queues Supporting Other Functions 454 Laravel Horizon 454 Events 455 Firing an Event 456 Listening for an Event 457 Broadcasting Events Over WebSockets, and Laravel Echo 461 Configuration and Setup 462 Broadcasting an Event 462 Receiving the Message 465 Advanced Broadcasting Tools 467 Laravel Echo (the JavaScript Side) 471 Scheduler 475 Available Task Types 476 Available Time Frames 476 Defining Time Zones for Scheduled Commands 478 Blocking and Overlap 479 Handling Task Output 479 Task Hooks 480 Running the Scheduler in Local Development 480 Testing 480 TL;DR 482 17. Helpers and Collections. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 483 Helpers 483 Arrays 483 Strings 486 Application Paths 489 URLs 490 Miscellaneous 492 Collections 495 The Basics 495 A Few Collection Operations 497 TL;DR 503 18. The Laravel Ecosystem. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 505 Tools Covered in This Book 505 Valet 505 Homestead 505 Herd 506 The Laravel Installer 506 Dusk 506 Passport 506 Sail 506 Sanctum 506 Fortify 507 Breeze 507 Jetstream 507 Horizon 507 Echo 507 Tools Not Covered in This Book 507 Forge 508 Vapor 508 Envoyer 508 Cashier 509 Socialite 509 Nova 509 Spark 510 Envoy 510 Telescope 510 Octane 510 Pennant 511 Folio 511 Volt 511 Pint 511 Other Resources 511 Glossary. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 513 Index. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 521
Stauffer Matt / Стаффер Мэтт - Laravel. Up and Running, 3rd Edition / Запускаем Laravel, 3-е издание [2024, PDF, EPUB, ENG] download torrent for free and without registration
You cannot post new topics in this forum You cannot reply to topics in this forum You cannot edit your posts in this forum You cannot delete your posts in this forum You cannot vote in polls in this forum You cannot attach files in this forum You can download files in this forum