laravel_quick_guide
Laravel - Quick Guide
Section titled “Laravel - Quick Guide”Laravel - Overview
Section titled “Laravel - Overview”Introduction
Section titled “Introduction”Laravel is a web application framework with expressive, elegant syntax. It adheres to the MVC (Model-View-Controller) architectural pattern and provides a vast ecosystem of tools and features like a powerful ORM (Eloquent), database migrations, a robust routing system, an integrated testing suite, and the Artisan command-line interface. Laravel aims to make common web development tasks, such as authentication, routing, sessions, and caching, easier and faster.
Being an open-source framework, Laravel benefits from a large community and offers a rich set of features that significantly boost web development speed and quality. For developers familiar with PHP, Laravel provides a structured and efficient way to build applications, reducing boilerplate code and enhancing security by mitigating common web vulnerabilities.
Laravel – Key Features
Section titled “Laravel – Key Features”- Eloquent ORM: An advanced ActiveRecord implementation for easy database interaction.
- Routing System: Simple and expressive way to define application routes.
- Blade Templating Engine: A powerful, yet simple templating language.
- Migrations & Seeding: Version control for your database schema and easy data population.
- Artisan Console: A command-line interface with helpful commands for common tasks.
- Testing: Built-in support for unit and feature testing with PHPUnit.
- Modularity & Composer: Easy dependency management and package integration.
- Security: Protection against common web vulnerabilities like XSS, CSRF, and SQL injection.
- Task Scheduling: A fluent API for scheduling recurring tasks.
- Queues: For deferring time-consuming tasks to background processing.
- Broadcasting & WebSockets: For building real-time applications.
- Authentication & Authorization: Simplified setup for user login, registration, and access control.
Laravel - Installation
Section titled “Laravel - Installation”Laravel uses Composer for dependency management. Ensure Composer is installed on your system before proceeding.
Step 1: Install Composer
Section titled “Step 1: Install Composer”Download and install Composer from https://getcomposer.org/download/. Verify installation with composer --version.
Step 2: Create a New Laravel Project
Section titled “Step 2: Create a New Laravel Project”Use Composer to create a new Laravel project:
composer create-project laravel/laravel example-appReplace example-app with your project’s name. This downloads Laravel and its dependencies.
Step 3: Run the Development Server
Section titled “Step 3: Run the Development Server”Navigate into your project directory (cd example-app) and start the Artisan development server:
php artisan serveThis typically starts the server at http://127.0.0.1:8000.
Step 4: Access Your Application
Section titled “Step 4: Access Your Application”Open http://127.0.0.1:8000 in your browser. You should see the Laravel welcome page.
For detailed system requirements and alternative installation methods like Laravel Sail (Docker), refer to the Laravel Installation Guide section.
Laravel - Application Structure
Section titled “Laravel - Application Structure”Root Directory
Section titled “Root Directory”The root directory of a Laravel application contains several key folders:
app- Contains the core code of your application (Models, Controllers, Service Providers, etc.).bootstrap- Contains files that bootstrap the framework and configure autoloading, plus acachedirectory for framework-generated files.config- Contains all of your application’s configuration files.database- Contains your database migrations, model factories, and seeders.public- The document root for your application. It contains theindex.phpentry point and your assets (CSS, JS, images).resources- Contains your views (Blade templates), raw assets (like Sass or Less files if not using Vite/Mix defaults), and language files.routes- Contains all route definitions for your application (e.g.,web.php,api.php).storage- Contains compiled Blade templates, file-based sessions, file caches, logs, and other files generated by the framework. Also used for user-uploaded files.tests- Contains your automated tests (feature and unit tests).vendor- Contains your Composer dependencies.
app Directory
Section titled “app Directory”The app directory is where most of your application’s code resides. Key subdirectories include:
Console- Contains your custom Artisan commands.Exceptions- Contains your application’s custom exception handler.Http- Contains your Controllers, Middleware, and Form Requests.Jobs- Contains your queueable jobs.Listeners- Contains handler classes for your events.Mail- Contains your mailable classes for sending emails.Models- (Often created by developers, not always default) Contains your Eloquent model classes.Notifications- Contains notification classes.Policies- Contains authorization policy classes.Providers- Contains all of your application’s service providers.
Laravel - Configuration
Section titled “Laravel - Configuration”All configuration files for the Laravel framework are stored in the config directory. Each option is documented, so feel free to look through the files and get familiar with the options available to you.
Environment Configuration
Section titled “Environment Configuration”Laravel utilizes the DotEnv PHP library. Sensitive configuration values (database credentials, API keys, etc.) should be stored in the .env file at the root of your project. This file should not be committed to version control.
A .env.example file is included with Laravel. You should copy it to .env and modify it:
cp .env.example .envKey .env variables:
APP_NAME: Your application’s name.APP_ENV: The current environment (e.g.,local,production,testing).APP_KEY: A unique, 32-character string for encryption. Generate withphp artisan key:generate.APP_DEBUG: Set totruein local development to see detailed errors,falsein production.APP_URL: The base URL of your application.DB_CONNECTION,DB_HOST,DB_DATABASE, etc.: Database connection details.MAIL_MAILER,MAIL_HOST, etc.: Mail configuration.
Accessing Configuration Values
Section titled “Accessing Configuration Values”You can access configuration values using the config() helper function anywhere in your application:
$appName = config('app.name');$databaseConnection = config('database.default');Configuration Caching
Section titled “Configuration Caching”To boost performance in production, cache your configuration files:
php artisan config:cacheTo clear the cache: php artisan config:clear.
Maintenance Mode
Section titled “Maintenance Mode”When your application is in maintenance mode, a custom view will be displayed for all requests. This is useful when updating your application or performing scheduled maintenance.
Start Maintenance Mode:
php artisan downYou can also provide options for redirection or a secret bypass:
php artisan down --redirect=/maintenance --retry=60 --secret="your-bypass-token"Stop Maintenance Mode:
php artisan upCustomize the maintenance mode view by creating resources/views/errors/503.blade.php.
Laravel - Routing
Section titled “Laravel - Routing”Basic Routing
Section titled “Basic Routing”The most basic Laravel routes accept a URI and a Closure, providing a very simple and expressive method of defining routes. Routes are typically defined in routes/web.php for web interface routes and routes/api.php for API routes.
Available Router Methods:
Route::get($uri, $callback);Route::post($uri, $callback);Route::put($uri, $callback);Route::patch($uri, $callback);Route::delete($uri, $callback);Route::options($uri, $callback);Example (routes/web.php):
use Illuminate\Support\Facades\Route;
Route::get('/', function () { return view('welcome'); // Returns the welcome Blade view});
Route::get('/hello', function () { return 'Hello World!';});Routing to Controllers:
use App\Http\Controllers\UserController;
Route::get('/users', [UserController::class, 'index']);Route::get('/users/{id}', [UserController::class, 'show']);Route Parameters
Section titled “Route Parameters”Required Parameters:
Section titled “Required Parameters:”Sometimes you will need to capture segments of the URI within your route. For example, you may need to capture a user’s ID from the URL.
Route::get('/user/{id}', function (string $id) { return 'User ID: ' . $id;});Optional Parameters:
Section titled “Optional Parameters:”You may also specify route parameters that are not always present in the URI path. You may do so by placing a ? mark after the parameter name and providing a default value for the variable.
Route::get('/user/{name?}', function (string $name = 'Guest') { return 'Username: ' . $name;});Route Model Binding
Section titled “Route Model Binding”Laravel automatically injects model instances directly into your routes or controllers if a route segment name matches a type-hinted variable name. For example, instead of injecting a user’s ID, you can inject the entire User model instance that matches the given ID.
use App\Models\User;
Route::get('/users/{user}', function (User $user) { // {user} matches $user return $user->email;});Named Routes
Section titled “Named Routes”Named routes allow you to conveniently generate URLs or redirects for specific routes.
Route::get('/user/profile', [UserProfileController::class, 'show'])->name('profile.show');
// Generating URL:// $url = route('profile.show', ['id' => 1]);
// Redirecting:// return redirect()->route('profile.show', ['id' => 1]);Route Groups
Section titled “Route Groups”Route groups allow you to share route attributes, such as middleware or prefixes, across a large number of routes without needing to define those attributes on each individual route.
Route::middleware(['auth', 'admin'])->prefix('admin')->name('admin.')->group(function () { Route::get('/dashboard', [AdminDashboardController::class, 'index'])->name('dashboard'); Route::get('/users', [AdminUserController::class, 'index'])->name('users.index');});Laravel - Middleware
Section titled “Laravel - Middleware”Middleware provide a mechanism for filtering HTTP requests entering your application. They act as layers that requests pass through.
Define Middleware:
Section titled “Define Middleware:”Create middleware using php artisan make:middleware <MiddlewareName>.
Register Middleware:
Section titled “Register Middleware:”Register in app/Http/Kernel.php:
- Global:
$middlewarearray. - Groups:
$middlewareGroupsarray (e.g.,web,api). - Route Aliases:
$middlewareAliasesarray.
Middleware Parameters:
Section titled “Middleware Parameters:”Pass parameters from routes to middleware, e.g., middleware('role:editor'). The handle method receives these after $next.
Terminable Middleware:
Section titled “Terminable Middleware:”Perform tasks after the response is sent using a terminate method in the middleware.
For detailed examples, refer to the Laravel Middleware section.
Laravel - Controllers
Section titled “Laravel - Controllers”Controllers organize request handling logic into classes, typically stored in app/Http/Controllers.
Creating Controllers:
Section titled “Creating Controllers:”php artisan make:controller <ControllerName>
Resource Controllers:
Section titled “Resource Controllers:”php artisan make:controller PhotoController --resource generates a controller with CRUD methods. Use Route::resource('photos', PhotoController::class); to route.
Single Action Controllers:
Section titled “Single Action Controllers:”php artisan make:controller ProvisionServer --invokable creates a controller with an __invoke method.
Dependency Injection:
Section titled “Dependency Injection:”Laravel automatically injects dependencies (type-hinted in constructor or methods) via its service container.
For detailed examples, refer to the Laravel Controllers section.
Laravel - Request
Section titled “Laravel - Request”Laravel’s Illuminate\Http\Request class provides an object-oriented way to interact with the current HTTP request, including retrieving input, cookies, and files.
Retrieving Request Information:
Section titled “Retrieving Request Information:”You can type-hint Illuminate\Http\Request in your controller methods.
use Illuminate\Http\Request;
public function store(Request $request){ $path = $request->path(); // 'foo/bar' $url = $request->url(); // 'http://example.com/foo/bar' $fullUrl = $request->fullUrl(); // 'http://example.com/foo/bar?name=taylor' $method = $request->method(); // 'GET', 'POST', etc. $isPost = $request->isMethod('post');
// Check if path matches a pattern if ($request->is('admin/*')) { /* ... */ }}Retrieving Input:
Section titled “Retrieving Input:”$name = $request->input('name'); // From query string or form data$email = $request->input('email', 'default@example.com'); // With default value
// Retrieve all input as an array$allInput = $request->all();
// Retrieve only specific input$subset = $request->only(['username', 'password']);$except = $request->except(['credit_card']);
// Dynamic properties$name = $request->name;Retrieving Files:
Section titled “Retrieving Files:”if ($request->hasFile('photo') && $request->file('photo')->isValid()) { $file = $request->file('photo'); $path = $file->store('avatars', 'public'); // Store in storage/app/public/avatars}For a practical example of input retrieval in a form, see the Validation or File Uploading sections.
Laravel - Cookie
Section titled “Laravel - Cookie”Laravel provides a simple API for managing HTTP cookies. All cookies are encrypted and signed by default.
Setting Cookies:
Section titled “Setting Cookies:”Attach to a response: return response('Hello')->cookie('name', 'value', $minutes);
Queue with facade: Cookie::queue('name', 'value', $minutes);
Retrieving Cookies:
Section titled “Retrieving Cookies:”From request: $value = $request->cookie('name');
Using facade: $value = Cookie::get('name');
Deleting Cookies:
Section titled “Deleting Cookies:”Attach expired: return response('Deleted')->withoutCookie('name');
Queue forgotten: Cookie::queue(Cookie::forget('name'));
For detailed examples, refer to the Laravel Cookie section.
Laravel - Response
Section titled “Laravel - Response”All routes and controllers should return a response to be sent back to the user’s browser. Laravel provides several ways to return responses.
Basic Responses:
Section titled “Basic Responses:”Strings and arrays are automatically converted to HTTP responses.
Route::get('/', function () { return 'Hello World'; });Route::get('/array', function () { return [1, 2, 3]; }); // Becomes JSONResponse Objects:
Section titled “Response Objects:”For more control, use the response() helper or Illuminate\Http\Response class.
return response('Custom content', 200) ->header('Content-Type', 'text/plain') ->header('X-Custom-Header', 'value');JSON Responses:
Section titled “JSON Responses:”return response()->json(['name' => 'Abigail', 'state' => 'CA']);return response()->json(['error' => 'Not found'], 404);File Downloads:
Section titled “File Downloads:”return response()->download(storage_path('app/files/report.pdf'));return response()->download(storage_path('app/files/report.pdf'), 'user-report.pdf', $headers);View Responses and Redirections are covered in their respective sections.
Laravel - Views
Section titled “Laravel - Views”Views contain the HTML served by your application and separate your controller/application logic from your presentation logic. Views are stored in the resources/views directory.
Creating Views:
Section titled “Creating Views:”Create a file like resources/views/greeting.blade.php:
<!-- View stored in resources/views/greeting.blade.php --><html> <body> <h1>Hello, {{ $name }}</h1> </body></html>Returning Views:
Section titled “Returning Views:”Route::get('/greet', function () { return view('greeting', ['name' => 'James']);});Passing Data to Views:
Section titled “Passing Data to Views:”Data can be passed as an array as the second argument to view(), or using the with() method.
return view('profile', ['user' => $user]);// orreturn view('profile')->with('user', $user)->with('posts', $posts);Sharing Data with All Views:
Section titled “Sharing Data with All Views:”Use View::share('key', 'value') in the boot method of a service provider (e.g., AppServiceProvider).
Blade Templating Engine
Section titled “Blade Templating Engine”Blade is Laravel’s simple, yet powerful templating engine. Blade view files use the .blade.php extension.
Key Blade Directives:
{{ $variable }}: Display data (escaped by default).{!! $variable !!}: Display unescaped data (use with caution).@if,@elseif,@else,@endif: Conditional statements.@foreach,@forelse,@while,@for: Loops.@csrf: CSRF token field.@method('PUT'): Method spoofing for forms.@include('partials.header'): Include sub-views.@extends('layouts.app'): Inherit a master layout.@section('content') ... @endsection: Define content sections.@yield('title'): Display content of a section from child view.
Layouts Example:
Section titled “Layouts Example:”<html><head><title>@yield('title', 'My App')</title></head><body> @include('partials.nav') <div class="container"> @yield('content') </div></body></html>
// resources/views/home.blade.php@extends('layouts.app')
@section('title', 'Homepage')
@section('content') <p>This is the home page content.</p>@endsectionLaravel - Redirections
Section titled “Laravel - Redirections”Redirect responses are instances of Illuminate\Http\RedirectResponse, and contain the proper headers needed to redirect the user to another URL.
Basic Redirection:
Section titled “Basic Redirection:”return redirect('/home/dashboard');Redirecting to Named Routes:
Section titled “Redirecting to Named Routes:”return redirect()->route('profile.show', ['id' => 1]);Redirecting to Controller Actions:
Section titled “Redirecting to Controller Actions:”return redirect()->action([UserController::class, 'profile'], ['id' => 1]);Redirecting Back:
Section titled “Redirecting Back:”return back()->withInput(); // Redirects to previous location, with old input flashed to sessionRedirecting with Flashed Session Data:
Section titled “Redirecting with Flashed Session Data:”return redirect()->route('dashboard')->with('status', 'Profile updated!');// In dashboard.blade.php:// @if (session('status')) <div class="alert alert-success">{{ session('status') }}</div> @endifLaravel - Working With Database
Section titled “Laravel - Working With Database”Laravel supports MySQL, PostgreSQL, SQLite, and SQL Server. Configuration is in .env and config/database.php.
Migrations:
Section titled “Migrations:”Use migrations for schema version control: php artisan make:migration create_users_table. Run with php artisan migrate.
Query Builder:
Section titled “Query Builder:”Fluent interface for database queries: DB::table('users')->where('active', 1)->get();
Eloquent ORM:
Section titled “Eloquent ORM:”ActiveRecord implementation: User::where('active', 1)->orderBy('name')->get();
For detailed examples and raw SQL, refer to the Laravel Working With Database section.
Laravel - Errors and Logging
Section titled “Laravel - Errors and Logging”Errors
Section titled “Errors”Error and exception handling is configured in App\Exceptions\Handler. APP_DEBUG=true in .env shows detailed errors in development.
Logging
Section titled “Logging”Laravel uses the Monolog library. Configure logging channels in config/logging.php. Default log file is storage/logs/laravel.log. Use the Log facade:
use Illuminate\Support\Facades\Log;
Log::emergency($message);Log::alert($message);Log::critical($message);Log::error($message);Log::warning($message);Log::notice($message);Log::info($message);Log::debug($message);Laravel - Forms
Section titled “Laravel - Forms”Laravel does not include a built-in HTML form builder like older versions did with laravelcollective/html. Instead, you use standard HTML forms within your Blade templates.
Basic Form Structure (.blade.php):
Section titled “Basic Form Structure (.blade.php):”<form method="POST" action="{{ route('routeName') }}"> @csrf {{-- CSRF protection --}}
<div> <label for="email">Email Address</label> <input type="email" id="email" name="email" value="{{ old('email') }}" required> @error('email') <div class="alert alert-danger">{{ $message }}</div> @enderror </div>
<div> <label for="password">Password</label> <input type="password" id="password" name="password" required> @error('password') <div class="alert alert-danger">{{ $message }}</div> @enderror </div>
@if (false) {{-- Example for PUT/PATCH/DELETE requests --}} @method('PUT') {{-- Or PATCH, DELETE --}} @endif
<div> <button type="submit">Submit</button> </div></form>Key Elements:
Section titled “Key Elements:”@csrf: Generates a hidden input field containing the CSRF token.method="POST": Standard for form submissions that modify data.action="{{ route('routeName') }}": Use named routes for form actions.{{ old('input_name') }}: Repopulates the form with old input if validation fails.@error('input_name') ... @enderror: Displays validation errors for a specific field.@method('VERB'): ForPUT,PATCH, orDELETErequests, as HTML forms only supportGETandPOST.
For file uploads, add enctype="multipart/form-data" to the <form> tag. See the File Uploading section.
Laravel - Localization
Section titled “Laravel - Localization”Laravel’s localization features provide a convenient way to retrieve strings in various languages, allowing you to easily support multiple languages within your application.
Language Files:
Section titled “Language Files:”Language strings are stored in files within the lang directory (e.g., lang/en/messages.php, lang/es/messages.php). Or, for JSON based files: lang/en.json, lang/es.json.
PHP File Example (lang/en/messages.php):
<?php
return [ 'welcome' => 'Welcome to our application!', 'greeting' => 'Hello, :name!',];Retrieving Strings:
Section titled “Retrieving Strings:”Use the __ helper function or @lang Blade directive.
echo __('messages.welcome');// In Blade: {{ __('messages.welcome') }} or @lang('messages.welcome')
echo __('messages.greeting', ['name' => 'Taylor']);Setting the Locale:
Section titled “Setting the Locale:”The application’s default locale is set in config/app.php (locale). You can change the active locale at runtime:
use Illuminate\Support\Facades\App;
App::setLocale('es'); // Sets current locale to SpanishA common practice is to set the locale via a middleware based on a URL segment or user preference.
Laravel - Session
Section titled “Laravel - Session”HTTP applications are stateless. Sessions provide a way to store information about the user across multiple requests. Laravel ships with a variety of session backends (file, cookie, database, Memcached/Redis, etc.) configurable in config/session.php and .env (SESSION_DRIVER).
Accessing Session Data (Illuminate\Http\Request):
Section titled “Accessing Session Data (Illuminate\Http\Request):”// Store data$request->session()->put('key', 'value');
// Retrieve data$value = $request->session()->get('key', 'default');
// Check if data existsif ($request->session()->has('users')) { /* ... */ }
// Retrieve all data$allData = $request->session()->all();
// Remove an item$request->session()->forget('key');
// Remove all items$request->session()->flush();Global session() Helper:
Section titled “Global session() Helper:”session(['key' => 'value']); // Store$value = session('key', 'default'); // RetrieveFlash Data:
Section titled “Flash Data:”Flash data is stored in the session for only the next request.
$request->session()->flash('status', 'Task was successful!');// After redirect, in next request's view:// @if (session('status')) {{ session('status') }} @endifLaravel - Validation
Section titled “Laravel - Validation”Laravel provides several different approaches to validate your application’s incoming data. The most common is using the validate method available on all incoming HTTP requests, or creating Form Request classes.
Using the validate Method:
Section titled “Using the validate Method:”public function store(Request $request){ $validated = $request->validate([ 'title' => 'required|unique:posts|max:255', 'body' => 'required', 'publish_at' => 'nullable|date', ]);
// The validated data is available in $validated array // If validation fails, a RedirectResponse is automatically generated // or a JsonResponse with errors for AJAX requests.}Displaying Validation Errors in Blade:
Section titled “Displaying Validation Errors in Blade:”The $errors variable is automatically made available to all views. It’s an instance of Illuminate\Support\MessageBag.
@if ($errors->any()) <div class="alert alert-danger"> <ul> @foreach ($errors->all() as $error) <li>{{ $error }}</li> @endforeach </ul> </div>@endif
<!-- For a specific field -->@error('title') <div class="alert alert-danger">{{ $message }}</div>@enderrorAvailable Validation Rules:
Section titled “Available Validation Rules:”Laravel provides a vast number of validation rules, including required, email, unique, min, max, date, confirmed, image, in, alpha, etc. Refer to the official validation documentation for a complete list.
Form Requests:
Section titled “Form Requests:”For more complex validation, create Form Request classes using php artisan make:request StorePostRequest. These classes contain their own authorization and validation logic.
Laravel - File Uploading
Section titled “Laravel - File Uploading”HTML form must have enctype="multipart/form-data".
Controller Logic:
Section titled “Controller Logic:”$request->validate(['avatar' => 'required|image|mimes:jpeg,png|max:2048']);if ($request->hasFile('avatar')) { $path = $request->file('avatar')->store('avatars', 'public'); // Run `php artisan storage:link` to make public disk accessible}For detailed examples, refer to the Laravel File Uploading section.
Laravel - Sending Email
Section titled “Laravel - Sending Email”Laravel uses Symfony Mailer. Configure via .env and config/mail.php.
Mailables:
Section titled “Mailables:”Create mailable classes: php artisan make:mail OrderShipped. Configure sender, recipient, subject, and view in the mailable class.
Sending Mail:
Section titled “Sending Mail:”use Illuminate\Support\Facades\Mail;use App\Mail\OrderShipped;
Mail::to($recipient)->send(new OrderShipped($order));For detailed examples, refer to the Laravel Sending Email section.
Laravel - Ajax
Section titled “Laravel - Ajax”Handle client-side asynchronous requests. Remember CSRF protection.
CSRF Setup:
Section titled “CSRF Setup:”Add <meta name="csrf-token" content="{{ csrf_token() }}"> to Blade. Configure JS library (e.g., jQuery $.ajaxSetup or Axios) to send X-CSRF-TOKEN header.
Server Response:
Section titled “Server Response:”Return response()->json(['data' => $data]); from controller.
For detailed examples, refer to the Laravel Ajax section.
Laravel - Error Handling
Section titled “Laravel - Error Handling”All exceptions are handled by App\Exceptions\Handler class. It has report() (for logging) and render() (for HTTP response) methods.
HTTP Exceptions:
Section titled “HTTP Exceptions:”Use abort(404); or abort(500, 'Something went wrong.'); to generate HTTP error responses.
Custom Error Pages:
Section titled “Custom Error Pages:”Create Blade views in resources/views/errors/ (e.g., 404.blade.php, 503.blade.php) for custom error displays.
Laravel - Event Handling
Section titled “Laravel - Event Handling”Laravel’s events provide a simple observer implementation, allowing you to subscribe and listen for various events that occur in your application.
Creating Events & Listeners:
Section titled “Creating Events & Listeners:”`php artisan make:event PodcastProcessed``php artisan make:listener SendPodcastNotification --event=PodcastProcessed`Registering Events & Listeners:
Section titled “Registering Events & Listeners:”Typically, listeners are automatically discovered if they are in the App\Listeners directory and correctly type-hint the event in their handle method. Manual registration is done in App\Providers\EventServiceProvider’s $listen array:
protected $listen = [ \App\Events\PodcastProcessed::class => [ \App\Listeners\SendPodcastNotification::class, ],];Dispatching Events:
Section titled “Dispatching Events:”use App\Events\PodcastProcessed;
PodcastProcessed::dispatch($podcast); // Or event(new PodcastProcessed($podcast));Listener handle method:
public function handle(PodcastProcessed $event): void{ // Access $event->podcast and perform actions}Laravel - Facades
Section titled “Laravel - Facades”Facades provide a “static” interface to classes available in the application’s service container. They offer a terse, expressive syntax while maintaining testability.
Using Facades:
Section titled “Using Facades:”use Illuminate\Support\Facades\Cache;
Cache::put('key', 'value', $minutes);$value = Cache::get('key');Creating Custom Facades:
Section titled “Creating Custom Facades:”- Create a class with the functionality.
- Create a Facade class extending
Illuminate\Support\Facades\Facade, implementinggetFacadeAccessor()to return the service container binding key. - Bind your class in a service provider (e.g.,
App::bind('my-service', function() { return new MyService(); });). - (Optional) Add an alias for the facade in
config/app.php’saliasesarray.
Laravel - Security
Section titled “Laravel - Security”Laravel provides robust security features out of the box.
- Password Hashing: Uses
Hashfacade (Bcrypt by default):Hash::make('password'),Hash::check('plain-text', $hashedPassword). - Authentication: Built-in services for user login, registration, password reset. See
Authfacade. - Authorization (Gates & Policies): Fine-grained control over user permissions.
- CSRF Protection: Automatic protection for
POST,PUT,PATCH,DELETEroutes in thewebmiddleware group. Use@csrfin forms. - XSS Protection: Blade’s
{{ }}syntax automatically escapes output. Use{!! !!}with extreme caution. - SQL Injection Protection: Eloquent ORM and Query Builder use PDO parameter binding, protecting against SQL injection by default.
- Cookie Encryption & Signing: Cookies are automatically encrypted and signed.
- HTTPS: Enforce HTTPS for sensitive data using middleware or
URL::forceScheme('https')in a service provider.