From 9bd44c816996e680f0cf4d97e97b13944f9a9b46 Mon Sep 17 00:00:00 2001 From: Jess Date: Mon, 8 Nov 2021 20:12:32 -0500 Subject: [PATCH 01/14] Create laravel.md --- laravel.md | 202 +++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 202 insertions(+) create mode 100644 laravel.md diff --git a/laravel.md b/laravel.md new file mode 100644 index 0000000..68b3649 --- /dev/null +++ b/laravel.md @@ -0,0 +1,202 @@ +--- +title: Laravel +date: 2021-11-09 +icon: +background: bg-orange-500 +tags: + - web + - framework + - php +categories: + - Programming + - Framework +intro: | + [Laravel](https://laravel.com/docs/8.x/) is an expressive and progressive web application framework for PHP. + This cheat sheet provides a reference for common commands and features. +--- + + +Getting started {.cols-3} +--------------- + + +### Requirements +#### PHP +- PHP version >= 7.3 +- BCMath PHP Extension +- Ctype PHP Extension +- Fileinfo PHP Extension +- JSON PHP Extension +- Mbstring PHP Extension +- OpenSSL PHP Extension +- PDO PHP Extension +- Tokenizer PHP Extension +- XML PHP Extension + +#### Server +Ensure your web server directs all requests to your application's +`public/index.php` file +See: [Deployment](#deployment) + + +### Installation {.cols-2} +Local development with [Docker Desktop](https://www.docker.com/products/docker-desktop) and [Sail](https://laravel.com/docs/8.x/sail) +#### Windows +1. Install & enable [WSL2](https://docs.microsoft.com/en-us/windows/wsl/install) +2. Install [Docker Desktop](https://www.docker.com/products/docker-desktop) +3. Ensure that Docker Desktop is [configured to use WSL2](https://docs.docker.com/desktop/windows/wsl/) +4. In WSL2 terminal: +```bash +curl -s https://laravel.build/example-app | bash + +cd example-app + +./vendor/bin/sail up +``` +#### Mac +1. Install [Docker Desktop](https://www.docker.com/products/docker-desktop) +2. In terminal: +```bash +curl -s "https://laravel.build/example-app" | bash + +cd example-app + +./vendor/bin/sail up +``` +#### Linux +```bash +curl -s https://laravel.build/example-app | bash + +cd example-app + +./vendor/bin/sail up +``` +Installation via [Composer](https://getcomposer.org) +```bash +composer create-project laravel/laravel example-app + +cd example-app + +php artisan serve +``` + +Access application via http://localhost + + +### Configuration +#### .env +Retrieve values from `.env` file +```php +env('APP_DEBUG', false) +``` +Determine current environment +```php +use Illuminate\Support\Facades\App; + +$environment = App::environment(); +``` +Accessing configuration values using "dot" syntax +``` +// config/app.php $ +$value = config('app.timezone'); + +// Retrieve a default value if the configuration value does not exist... +$value = config('app.timezone', 'Asia/Seoul'); +``` + + + + +PHP Operators {.cols-4} +--------------- + + + +### Arithmetic +| - | - | +|------|----------------| +| `+` | Addition | +| `-` | Subtraction | +| `*` | Multiplication | +| `/` | Division | +| `%` | Modulo | +| `**` | Exponentiation | + +### Assignment +| - | - | +|----------|---------------------| +| `a += b` | Same as `a = a + b` | +| `a -= b` | Same as `a = a – b` | +| `a *= b` | Same as `a = a * b` | +| `a /= b` | Same as `a = a / b` | +| `a %= b` | Same as `a = a % b` | + + +### Comparison {.row-span-2} +| - | - | +|-------|------------------------------| +| `==` | Equal | +| `===` | Identical | +| `!=` | Not equal | +| `<>` | Not equal | +| `!==` | Not identical | +| `<` | Less than | +| `>` | Greater than | +| `<=` | Less than or equal | +| `>=` | Greater than or equal | +| `<=>` | Less than/equal/greater than | + +### Logical +| - | - | +|-------|--------------| +| `and` | And | +| `or` | Or | +| `xor` | Exclusive or | +| `!` | Not | +| `&&` | And | +| `||` | Or | + + + + +### Arithmetic {.col-span-2} +```php +// Arithmetic +$sum = 1 + 1; // 2 +$difference = 2 - 1; // 1 +$product = 2 * 2; // 4 +$quotient = 2 / 1; // 2 + +// Shorthand arithmetic +$num = 0; +$num += 1; // Increment $num by 1 +echo $num++; // Prints 1 (increments after evaluation) +echo ++$num; // Prints 3 (increments before evaluation) +$num /= $float; // Divide and assign the quotient to $num +``` + + + +### Bitwise +| - | - | +|------|--------------------| +| `&` | And | +| `|` | Or (inclusive or) | +| `^` | Xor (exclusive or) | +| `~` | Not | +| `<<` | Shift left | +| `>>` | Shift right | + + + + + +Also see +------- + +- [PHP Docs](https://www.php.net/manual/en/index.php) +- [Learn X in Y minutes](https://learnxinyminutes.com/docs/php/) + + + + From 1adc8b4787f1e966240c9fe32a2f22fcabbf928f Mon Sep 17 00:00:00 2001 From: Jess Date: Mon, 8 Nov 2021 20:32:49 -0500 Subject: [PATCH 02/14] add maintenance mode --- laravel.md | 67 ++++++++++++++++++++++++++++++++++++++++++++++++++---- 1 file changed, 62 insertions(+), 5 deletions(-) diff --git a/laravel.md b/laravel.md index 68b3649..4cba6cc 100644 --- a/laravel.md +++ b/laravel.md @@ -83,11 +83,14 @@ php artisan serve Access application via http://localhost -### Configuration -#### .env +Configuration {.cols-3} +--------------- + + +### .env {.cols-2} Retrieve values from `.env` file ```php -env('APP_DEBUG', false) +env('APP_DEBUG', false); ``` Determine current environment ```php @@ -96,15 +99,69 @@ use Illuminate\Support\Facades\App; $environment = App::environment(); ``` Accessing configuration values using "dot" syntax -``` -// config/app.php $ +```php +// config/app.php --> ['timezone' => ''] $value = config('app.timezone'); // Retrieve a default value if the configuration value does not exist... $value = config('app.timezone', 'Asia/Seoul'); ``` +Set configuration values at runtime: +```php +config(['app.timezone' => 'America/Chicago']); +``` +### Debug Mode +On (local dev): +```php +// .env file +APP_ENV=local +APP_DEBUG=true +// ... +``` +Off (production): +```php +// .env file +APP_ENV=production +APP_DEBUG=false +// ... +``` +### Maintenance Mode +Temporarily disable application (503 status code) +```bash +php artisan down +``` +Set `Refresh` HTTP header +```bash +// auto refresh browser after 60 seconds +php artisan down --refresh=15 +``` +Set `Retry-After` HTTP header +```bash +// retry after 60 seconds +php artisan down --retry=60 +``` +#### Bypass Maintenance Mode +```bash +php artisan down --secret="1630542a-246b-4b66-afa1-dd72a4c43515" +``` +#### Pre-Render Maintenance View +```bash +php artisan down --render="errors::503" +``` +#### Redirect instead of maintenance view +```bash +php artisan down --redirect=/ +``` +#### Disable maintenance mode +```bash +php artisan up +``` +### Customize maintenance template +``` +resources/views/errors/503.blade.php +``` PHP Operators {.cols-4} From 6299977874a2d8ad5e3f5cb23b13bc04ba65376b Mon Sep 17 00:00:00 2001 From: Jess Date: Mon, 8 Nov 2021 21:11:52 -0500 Subject: [PATCH 03/14] add some routing --- laravel.md | 188 ++++++++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 186 insertions(+), 2 deletions(-) diff --git a/laravel.md b/laravel.md index 4cba6cc..42945ae 100644 --- a/laravel.md +++ b/laravel.md @@ -35,7 +35,7 @@ Getting started {.cols-3} #### Server Ensure your web server directs all requests to your application's -`public/index.php` file +`public/index.php` file See: [Deployment](#deployment) @@ -164,9 +164,193 @@ resources/views/errors/503.blade.php ``` -PHP Operators {.cols-4} +Routing {.cols-4} --------------- +Web routes - `routes/web.php` +API routes - `routes/api.php` + +### Router Methods +```php +Route::get($uri, $callback); +Route::post($uri, $callback); +Route::put($uri, $callback); +Route::patch($uri, $callback); +Route::delete($uri, $callback); +Route::options($uri, $callback); +``` +Multiple HTTP methods +```php +Route::match(['get', 'post'], '/', function () { + // +}); + +Route::any('/', function () { + // +}); +``` + +### Basic +```php +use Illuminate\Support\Facades\Route; + +// closure +Route::get('/greeting', function () { + return 'Hello World'; +}); + +// controller action +Route::get( + '/user/profile', + [UserProfileController::class, 'show'] +); +``` + +### Dependency Injection +Type hint concrete dependencies for auto-injection +```php +use Illuminate\Http\Request; + +Route::get('/users', function (Request $request) { + // ... +}); +``` + +### Redirect Routes +HTTP 302 status +```php +Route::redirect('/here', '/there'); +``` +Set the status code +```php +Route::redirect('/here', '/there', 301); +``` +Permanent 301 redirect +```php +Route::permanentRedirect('/here', '/there'); +``` + +### View Routes +```php +Route::view('/welcome', 'welcome'); + +// with data +Route::view('/welcome', 'welcome', ['name' => 'Taylor']); +``` + +### Route Parameters {.cols-2} +#### Required params +```php +Route::get('/user/{id}', function ($id) { + return 'User '.$id; +}); +``` +With dependency injection +```php +use Illuminate\Http\Request; + +Route::get('/user/{id}', function (Request $request, $id) { + return 'User '.$id; +}); +``` +#### Optional Paramters +```php +Route::get('/user/{name?}', function ($name = null) { + return $name; +}); + +Route::get('/user/{name?}', function ($name = 'John') { + return $name; +}); +``` +### Regular Expression Constraints {.cols-2} +```php +Route::get('/user/{name}', function ($name) { + // +})->where('name', '[A-Za-z]+'); + +Route::get('/user/{id}', function ($id) { + // +})->where('id', '[0-9]+'); + +Route::get('/user/{id}/{name}', function ($id, $name) { + // +})->where(['id' => '[0-9]+', 'name' => '[a-z]+']); +``` +Common pattern helpers +```php +Route::get('/user/{id}/{name}', function ($id, $name) { + // +})->whereNumber('id')->whereAlpha('name'); + +Route::get('/user/{name}', function ($name) { + // +})->whereAlphaNumeric('name'); + +Route::get('/user/{id}', function ($id) { + // +})->whereUuid('id'); +``` + +### Global Constraint +Always apply constraint to paramters with this name +```php +// in App\Providers\RouteServiceProvider +public function boot() +{ + Route::pattern('id', '[0-9]+'); +} + + +// in routes/web.php +Route::get('/user/{id}', function ($id) { + // Only executed if {id} is numeric... +}); +``` + +### Named Routes +Route names should always be unique +```php +Route::get('/user/profile', function () { + // +})->name('profile'); +``` +See: [Helpers](#helpers) + + + +Helpers {.cols-3} +--------------- +### routes +#### Named route +```php +$url = route('profile'); +``` +With parameters +```php +// Route::get('/user/{id}/profile', /*...*/ )->name('profile); + +$url = route('profile', ['id' => 1]); + +// /user/1/profile/ +``` +Additional parameters will be added to query string +```php +// Route::get('/user/{id}/profile', /*...*/ )->name('profile); + +$url = route('profile', ['id' => 1, 'photos'=>'yes']); + +// /user/1/profile?photos=yes +``` +#### Redirects +```php +// Generating Redirects... +return redirect()->route('profile'); +``` + + + + ### Arithmetic From f0cd0376a9f52d13160ade1a08b5a49f6e4801d5 Mon Sep 17 00:00:00 2001 From: Jess Date: Mon, 8 Nov 2021 21:43:28 -0500 Subject: [PATCH 04/14] finish routes --- laravel.md | 221 ++++++++++++++++++++++++++++++++++------------------- 1 file changed, 144 insertions(+), 77 deletions(-) diff --git a/laravel.md b/laravel.md index 42945ae..a4cac91 100644 --- a/laravel.md +++ b/laravel.md @@ -318,6 +318,148 @@ Route::get('/user/profile', function () { See: [Helpers](#helpers) +### Route Groups {.cols-2} +Share attributes across routes +#### Middleware +```php +Route::middleware(['first', 'second'])->group(function () { + Route::get('/', function () { + // Uses first & second middleware... + }); + + Route::get('/user/profile', function () { + // Uses first & second middleware... + }); +}); +``` +#### Subdomain +*Register subdomain routes before registering root domain routes* +```php +Route::domain('{account}.example.com')->group(function () { + Route::get('user/{id}', function ($account, $id) { + // + }); +}); +``` +#### Prefixes +URI prefix +```php +Route::prefix('admin')->group(function () { + Route::get('/users', function () { + // Matches The "/admin/users" URL + }); +}); +``` +Name Prefix +```php +Route::name('admin.')->group(function () { + Route::get('/users', function () { + // Route assigned name "admin.users"... + })->name('users'); +}); +``` + +### Route Model Binding {.cols-2} +Convenient way to automatically inject the model instances directly into your routes +#### Implicit binding +With closure +```php +use App\Models\User; + +Route::get('/users/{user}', function (User $user) { + return $user->email; +}); + +// /user/1 --> User::where('id', '=', 1); +``` +With controller action +```php +use App\Http\Controllers\UserController; +use App\Models\User; + +// Route definition... +Route::get('/users/{user}', [UserController::class, 'show']); + +// Controller method definition... +public function show(User $user) +{ + return view('user.profile', ['user' => $user]); +} +``` +With custom resolution column +```php +use App\Models\Post; + +Route::get('/posts/{post:slug}', function (Post $post) { + return $post; +}); + +// /posts/my-post --> Post::where('slug', '=', 'my-post'); +``` +Always use a different column to resolve +```php +// in App\Models\Post +public function getRouteKeyName() +{ + return 'slug'; +} +``` +Multiple models - second is child of first +```php +use App\Models\Post; +use App\Models\User; + +Route::get('/users/{user}/posts/{post:slug}', function (User $user, Post $post) { + return $post; +}); +``` +#### Explicit Binding +Define how route parameters correspond to models +```php +// in App\Providers\RouteServiceProvider +use App\Models\User; +use Illuminate\Support\Facades\Route; + +public function boot() +{ + Route::model('user', User::class); + + // ... +} +``` +Define custom binding logic +```php +// in App\Providers\RouteServiceProvider +use App\Models\User; +use Illuminate\Support\Facades\Route; + +public function boot() +{ + Route::bind('user', function ($value) { + return User::where('name', $value)->firstOrFail(); + }); + + // ... +} +``` + +### Fallback Routes +Executed when no other routes match +```php +Route::fallback(function () { + // +}); +``` + +### Accessing current route +```php +use Illuminate\Support\Facades\Route; + +$route = Route::current(); // Illuminate\Routing\Route +$name = Route::currentRouteName(); // string +$action = Route::currentRouteAction(); // string +``` + Helpers {.cols-3} --------------- @@ -349,87 +491,12 @@ return redirect()->route('profile'); ``` +Deployment {.cols-3} +--------------- -### Arithmetic -| - | - | -|------|----------------| -| `+` | Addition | -| `-` | Subtraction | -| `*` | Multiplication | -| `/` | Division | -| `%` | Modulo | -| `**` | Exponentiation | - -### Assignment -| - | - | -|----------|---------------------| -| `a += b` | Same as `a = a + b` | -| `a -= b` | Same as `a = a – b` | -| `a *= b` | Same as `a = a * b` | -| `a /= b` | Same as `a = a / b` | -| `a %= b` | Same as `a = a % b` | - - -### Comparison {.row-span-2} -| - | - | -|-------|------------------------------| -| `==` | Equal | -| `===` | Identical | -| `!=` | Not equal | -| `<>` | Not equal | -| `!==` | Not identical | -| `<` | Less than | -| `>` | Greater than | -| `<=` | Less than or equal | -| `>=` | Greater than or equal | -| `<=>` | Less than/equal/greater than | - -### Logical -| - | - | -|-------|--------------| -| `and` | And | -| `or` | Or | -| `xor` | Exclusive or | -| `!` | Not | -| `&&` | And | -| `||` | Or | - - - - -### Arithmetic {.col-span-2} -```php -// Arithmetic -$sum = 1 + 1; // 2 -$difference = 2 - 1; // 1 -$product = 2 * 2; // 4 -$quotient = 2 / 1; // 2 - -// Shorthand arithmetic -$num = 0; -$num += 1; // Increment $num by 1 -echo $num++; // Prints 1 (increments after evaluation) -echo ++$num; // Prints 3 (increments before evaluation) -$num /= $float; // Divide and assign the quotient to $num -``` - - - -### Bitwise -| - | - | -|------|--------------------| -| `&` | And | -| `|` | Or (inclusive or) | -| `^` | Xor (exclusive or) | -| `~` | Not | -| `<<` | Shift left | -| `>>` | Shift right | - - - Also see From 254db2e57e768c4224d73dacc8e28c44922db190 Mon Sep 17 00:00:00 2001 From: Jess Date: Mon, 8 Nov 2021 21:49:05 -0500 Subject: [PATCH 05/14] typo --- laravel.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/laravel.md b/laravel.md index a4cac91..84ec77f 100644 --- a/laravel.md +++ b/laravel.md @@ -253,7 +253,7 @@ Route::get('/user/{id}', function (Request $request, $id) { return 'User '.$id; }); ``` -#### Optional Paramters +#### Optional Parameters ```php Route::get('/user/{name?}', function ($name = null) { return $name; From e3259292ff65e6834b47d8a611f8fdbb58ef64aa Mon Sep 17 00:00:00 2001 From: Jess Date: Mon, 8 Nov 2021 21:56:19 -0500 Subject: [PATCH 06/14] add "also see" links --- laravel.md | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/laravel.md b/laravel.md index 84ec77f..4383e8d 100644 --- a/laravel.md +++ b/laravel.md @@ -502,8 +502,9 @@ Deployment {.cols-3} Also see ------- -- [PHP Docs](https://www.php.net/manual/en/index.php) -- [Learn X in Y minutes](https://learnxinyminutes.com/docs/php/) +- [Laravel Docs](https://laravel.com/docs/8.x) +- [Laracasts](https://laracasts.com/) +- [Laravel API](https://laravel.com/api/8.x/) From 65f61ca75b303a3152e6db4721aa274103c22565 Mon Sep 17 00:00:00 2001 From: Jess Date: Mon, 8 Nov 2021 22:07:04 -0500 Subject: [PATCH 07/14] begin controllers --- laravel.md | 57 +++++++++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 56 insertions(+), 1 deletion(-) diff --git a/laravel.md b/laravel.md index 4383e8d..726ec75 100644 --- a/laravel.md +++ b/laravel.md @@ -491,11 +491,66 @@ return redirect()->route('profile'); ``` -Deployment {.cols-3} +Controllers {.cols-3} --------------- +### Basic +```php +namespace App\Http\Controllers; +use App\Http\Controllers\Controller; +use App\Models\User; +class UserController extends Controller +{ + /** + * Show the profile for a given user. + * + * @param int $id + * @return \Illuminate\View\View + */ + public function show($id) + { + return view('user.profile', [ + 'user' => User::findOrFail($id) + ]); + } +} +``` +Define a route to this controller method: +```php +use App\Http\Controllers\UserController; + +Route::get('/user/{id}', [UserController::class, 'show']); +``` + +### Single Action +```php +namespace App\Http\Controllers; + +use App\Http\Controllers\Controller; +use App\Models\User; + +class ProvisionServer extends Controller +{ + /** + * Provision a new web server. + * + * @return \Illuminate\Http\Response + */ + public function __invoke() + { + // ... + } +} +``` +Define the route: +```php +use App\Http\Controllers\ProvisionServer; + +Route::post('/server', ProvisionServer::class); +``` +See: [Artisan Commands](#artisan-commands) From 81d9698002a94eaf221ffb5c691204f5ea752f01 Mon Sep 17 00:00:00 2001 From: Jess Date: Tue, 9 Nov 2021 19:45:24 -0500 Subject: [PATCH 08/14] begin request --- laravel.md | 290 +++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 290 insertions(+) diff --git a/laravel.md b/laravel.md index 726ec75..fa65935 100644 --- a/laravel.md +++ b/laravel.md @@ -554,6 +554,296 @@ See: [Artisan Commands](#artisan-commands) +Requests {.cols-3} +--------------- +### CSRF Protection +Laravel automatically generates a CSRF "token" for each active user session. +This token is used to verify that the authenticated user is the person actually making the requests. + +Get current session's token: +```php +Route::get('/token', function (Request $request) { + $token = $request->session()->token(); + + $token = csrf_token(); + + // ... +}); +``` +POST, PUT, PATCH, or DELETE forms should include a hidden CSRF `_token` field +in the form to validate the request. +```html +
+ @csrf + + + +
+``` +#### Exclude URIs From CSRF Protection +Define routes outside of the `routes/web.php` +Or +Adding route URIs to the `$except` property of `VerifyCsrfToken` +```php +use Illuminate\Foundation\Http\Middleware\VerifyCsrfToken as Middleware; + +class VerifyCsrfToken extends Middleware +{ + protected $except = [ + 'stripe/*', + 'http://example.com/foo/bar', + 'http://example.com/foo/*', + ]; +} +``` + +### Accessing Request +Get an instance of the current request by type-hinting the +controller action or route closure +```php +// controller action +class UaerController extends Controller +{ + public function store(Request $request) + { + $name = $request->input('name'); + } +} + +// closure +Route::get('/', function (Request $request) { + // +}); +``` +[See Routing](#routing) + +### Path +The request's path information +```php +$uri = $request->path(); + +// http://example.com/foo/bar --> foo/bar +``` +#### Match path to pattern +Verify that the incoming request path matches a given pattern +```php +// * is wildcard +if ($request->is('admin/*')) { + // +} +``` +Determine if the incoming request matches a named route +```php +if ($request->routeIs('admin.*')) { + // +} +``` +#### URL +Full URL for the incoming request +```php +// URL without the query string +$url = $request->url(); + +$urlWithQueryString = $request->fullUrl(); + +// append data to query string +$request->fullUrlWithQuery(['type' => 'phone']); +``` + +### Request Method + +```php +$method = $request->method(); + +// verify that the HTTP verb matches a given string +if ($request->isMethod('post')) { + // +} +``` + +### Headers +```php +$value = $request->header('X-Header-Name'); + +$value = $request->header('X-Header-Name', 'default value'); + +// determine if the request contains a given header +if ($request->hasHeader('X-Header-Name')) { + // +} + +// retrieve a bearer token from the Authorization header +$token = $request->bearerToken(); +``` + +### Client IP +```php +$ipAddress = $request->ip(); +``` + +### Content +Return an array containing all of the content types accepted by the request +```php +$contentTypes = $request->getAcceptableContentTypes(); +``` +Boolean check for content types are accepted by the request +```php +if ($request->accepts(['text/html', 'application/json'])) { + // ... +} +``` +Determine content type is most preferred by the request +```php +$preferred = $request->prefers(['text/html', 'application/json']); +``` +Shortcut to determine if the incoming request expects a JSON response +```php +if ($request->expectsJson()) { + // ... +} +``` + +### Input +Retrieve all of the incoming request's input data as an array +```php +$input = $request->all(); +``` +Retrieve all of the incoming request's input data as a collection +```php +$input = $request->collect(); + +// retrieve subset as collection +$request->collect('users')->each(function ($user) { + // ... +}); +``` +[See helpers](#helpers) + +Retrieve user input (also gets values from query string) +```php +$name = $request->input('name'); + +// with default value if none present +$name = $request->input('name', 'Sally'); +``` + +Access array inputs +```php +$name = $request->input('products.0.name'); + +$names = $request->input('products.*.name'); +``` + +Retrieve all of the input values as an associative array: +```php +$input = $request->input(); +``` + +Only retrieve values from the query string: +```php +$name = $request->query('name'); + +// with default value +$name = $request->query('name', 'Helen'); +``` + +Retrieve all of the query string values as an associative array: +```php +$query = $request->query(); +``` + +#### Boolean Input Values +Helpful for checkbox inputs or other booleans. +Return `true` for 1, "1", true, "true", "on", and "yes". +All other values will return `false` +```php +$archived = $request->boolean('archived'); +``` + +### Dynamic Properties +Access inputs via properties. If not found as an input, the route parameters will be checked. +```php +$name = $request->name; +``` + +### Retrieve Partial Input +```php +$input = $request->only(['username', 'password']); + +$input = $request->only('username', 'password'); + +$input = $request->except(['credit_card']); + +$input = $request->except('credit_card'); +``` + +### Check Existence +Determine if value(s) present +```php +if ($request->has('name')) { + // +} + +// check if ALL values are present +if ($request->has(['name', 'email'])) { + // +} + +// if any values are present +if ($request->hasAny(['name', 'email'])) { + // +} +``` +Execute the given closure if a value is present +```php +$request->whenHas('name', function ($input) { + // +}); + +// execute 2nd closure if value is **not** present +$request->whenHas('name', function ($input) { + // The "name" value is present... +}, function () { + // The "name" value is not present... +}); +``` + +Check if value exists and is not empty +```php +if ($request->filled('name')) { + // +} +``` + +Execute if value present and not empty +```php +$request->whenFilled('name', function ($input) { + // +}); + +// execute 2nd closure if value is not filled +$request->whenFilled('name', function ($input) { + // The "name" value is filled... +}, function () { + // The "name" value is not filled... +}); +``` + +Determine if key is absent +```php +if ($request->missing('name')) { + // +} +``` + +### Old Input + + + + + + + Also see ------- From 0ad11a7326e76a09f7028512a860f5ab4a0dcec5 Mon Sep 17 00:00:00 2001 From: jessinthecloud Date: Mon, 15 Nov 2021 18:25:43 -0500 Subject: [PATCH 09/14] init - specify laravel version --- laravel.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/laravel.md b/laravel.md index fa65935..8630eb8 100644 --- a/laravel.md +++ b/laravel.md @@ -12,7 +12,7 @@ categories: - Framework intro: | [Laravel](https://laravel.com/docs/8.x/) is an expressive and progressive web application framework for PHP. - This cheat sheet provides a reference for common commands and features. + This cheat sheet provides a reference for common commands and features for Laravel 8. --- From 9c34e31d9fde395c3ba26d754d1bb107607fab44 Mon Sep 17 00:00:00 2001 From: jessinthecloud Date: Mon, 15 Nov 2021 19:04:57 -0500 Subject: [PATCH 10/14] fix some typos --- laravel.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/laravel.md b/laravel.md index 8630eb8..cc5e460 100644 --- a/laravel.md +++ b/laravel.md @@ -158,7 +158,7 @@ php artisan down --redirect=/ ```bash php artisan up ``` -### Customize maintenance template +#### Customize maintenance template ``` resources/views/errors/503.blade.php ``` @@ -293,7 +293,7 @@ Route::get('/user/{id}', function ($id) { ``` ### Global Constraint -Always apply constraint to paramters with this name +Always apply constraint to parameters with this name ```php // in App\Providers\RouteServiceProvider public function boot() @@ -681,7 +681,7 @@ $token = $request->bearerToken(); $ipAddress = $request->ip(); ``` -### Content +### Content Type Return an array containing all of the content types accepted by the request ```php $contentTypes = $request->getAcceptableContentTypes(); From 2ccf923ec7f0cc540a179b686ba1246e973dc586 Mon Sep 17 00:00:00 2001 From: jessinthecloud Date: Tue, 16 Nov 2021 18:41:47 -0500 Subject: [PATCH 11/14] remove non-basic refs --- laravel.md | 264 ++++++++++++++--------------------------------------- 1 file changed, 70 insertions(+), 194 deletions(-) diff --git a/laravel.md b/laravel.md index cc5e460..305eacb 100644 --- a/laravel.md +++ b/laravel.md @@ -132,37 +132,15 @@ Temporarily disable application (503 status code) ```bash php artisan down ``` -Set `Refresh` HTTP header -```bash -// auto refresh browser after 60 seconds -php artisan down --refresh=15 -``` -Set `Retry-After` HTTP header -```bash -// retry after 60 seconds -php artisan down --retry=60 -``` #### Bypass Maintenance Mode ```bash php artisan down --secret="1630542a-246b-4b66-afa1-dd72a4c43515" ``` -#### Pre-Render Maintenance View -```bash -php artisan down --render="errors::503" -``` -#### Redirect instead of maintenance view -```bash -php artisan down --redirect=/ ``` #### Disable maintenance mode ```bash php artisan up ``` -#### Customize maintenance template -``` -resources/views/errors/503.blade.php -``` - Routing {.cols-4} --------------- @@ -239,7 +217,7 @@ Route::view('/welcome', 'welcome', ['name' => 'Taylor']); ``` ### Route Parameters {.cols-2} -#### Required params +#### Required parameters ```php Route::get('/user/{id}', function ($id) { return 'User '.$id; @@ -277,36 +255,6 @@ Route::get('/user/{id}/{name}', function ($id, $name) { // })->where(['id' => '[0-9]+', 'name' => '[a-z]+']); ``` -Common pattern helpers -```php -Route::get('/user/{id}/{name}', function ($id, $name) { - // -})->whereNumber('id')->whereAlpha('name'); - -Route::get('/user/{name}', function ($name) { - // -})->whereAlphaNumeric('name'); - -Route::get('/user/{id}', function ($id) { - // -})->whereUuid('id'); -``` - -### Global Constraint -Always apply constraint to parameters with this name -```php -// in App\Providers\RouteServiceProvider -public function boot() -{ - Route::pattern('id', '[0-9]+'); -} - - -// in routes/web.php -Route::get('/user/{id}', function ($id) { - // Only executed if {id} is numeric... -}); -``` ### Named Routes Route names should always be unique @@ -332,15 +280,6 @@ Route::middleware(['first', 'second'])->group(function () { }); }); ``` -#### Subdomain -*Register subdomain routes before registering root domain routes* -```php -Route::domain('{account}.example.com')->group(function () { - Route::get('user/{id}', function ($account, $id) { - // - }); -}); -``` #### Prefixes URI prefix ```php @@ -413,36 +352,6 @@ Route::get('/users/{user}/posts/{post:slug}', function (User $user, Post $post) return $post; }); ``` -#### Explicit Binding -Define how route parameters correspond to models -```php -// in App\Providers\RouteServiceProvider -use App\Models\User; -use Illuminate\Support\Facades\Route; - -public function boot() -{ - Route::model('user', User::class); - - // ... -} -``` -Define custom binding logic -```php -// in App\Providers\RouteServiceProvider -use App\Models\User; -use Illuminate\Support\Facades\Route; - -public function boot() -{ - Route::bind('user', function ($value) { - return User::where('name', $value)->firstOrFail(); - }); - - // ... -} -``` - ### Fallback Routes Executed when no other routes match ```php @@ -503,12 +412,6 @@ use App\Models\User; class UserController extends Controller { - /** - * Show the profile for a given user. - * - * @param int $id - * @return \Illuminate\View\View - */ public function show($id) { return view('user.profile', [ @@ -524,35 +427,6 @@ use App\Http\Controllers\UserController; Route::get('/user/{id}', [UserController::class, 'show']); ``` -### Single Action -```php -namespace App\Http\Controllers; - -use App\Http\Controllers\Controller; -use App\Models\User; - -class ProvisionServer extends Controller -{ - /** - * Provision a new web server. - * - * @return \Illuminate\Http\Response - */ - public function __invoke() - { - // ... - } -} -``` -Define the route: -```php -use App\Http\Controllers\ProvisionServer; - -Route::post('/server', ProvisionServer::class); -``` -See: [Artisan Commands](#artisan-commands) - - Requests {.cols-3} --------------- @@ -580,22 +454,6 @@ in the form to validate the request. ``` -#### Exclude URIs From CSRF Protection -Define routes outside of the `routes/web.php` -Or -Adding route URIs to the `$except` property of `VerifyCsrfToken` -```php -use Illuminate\Foundation\Http\Middleware\VerifyCsrfToken as Middleware; - -class VerifyCsrfToken extends Middleware -{ - protected $except = [ - 'stripe/*', - 'http://example.com/foo/bar', - 'http://example.com/foo/*', - ]; -} -``` ### Accessing Request Get an instance of the current request by type-hinting the @@ -651,7 +509,6 @@ $request->fullUrlWithQuery(['type' => 'phone']); ``` ### Request Method - ```php $method = $request->method(); @@ -682,7 +539,7 @@ $ipAddress = $request->ip(); ``` ### Content Type -Return an array containing all of the content types accepted by the request +Return an array containing all the content types accepted by the request ```php $contentTypes = $request->getAcceptableContentTypes(); ``` @@ -704,11 +561,11 @@ if ($request->expectsJson()) { ``` ### Input -Retrieve all of the incoming request's input data as an array +Retrieve all the incoming request's input data as an array ```php $input = $request->all(); ``` -Retrieve all of the incoming request's input data as a collection +Retrieve all the incoming request's input data as a collection ```php $input = $request->collect(); @@ -734,7 +591,7 @@ $name = $request->input('products.0.name'); $names = $request->input('products.*.name'); ``` -Retrieve all of the input values as an associative array: +Retrieve all the input values as an associative array: ```php $input = $request->input(); ``` @@ -747,7 +604,7 @@ $name = $request->query('name'); $name = $request->query('name', 'Helen'); ``` -Retrieve all of the query string values as an associative array: +Retrieve all the query string values as an associative array: ```php $query = $request->query(); ``` @@ -794,52 +651,75 @@ if ($request->hasAny(['name', 'email'])) { // } ``` -Execute the given closure if a value is present -```php -$request->whenHas('name', function ($input) { - // -}); - -// execute 2nd closure if value is **not** present -$request->whenHas('name', function ($input) { - // The "name" value is present... -}, function () { - // The "name" value is not present... -}); -``` - -Check if value exists and is not empty -```php -if ($request->filled('name')) { - // -} -``` - -Execute if value present and not empty -```php -$request->whenFilled('name', function ($input) { - // -}); - -// execute 2nd closure if value is not filled -$request->whenFilled('name', function ($input) { - // The "name" value is filled... -}, function () { - // The "name" value is not filled... -}); -``` - -Determine if key is absent -```php -if ($request->missing('name')) { - // -} -``` ### Old Input +Retrieve input from the previous request +```php +$username = $request->old('username'); +``` +Or use the `old()` helper +```php + +``` +See: (Helpers)[#helpers] + +### Uploaded Files +Retrieve uploaded file from request +```php +$file = $request->file('photo'); + +$file = $request->photo; +``` + +Get file path or extension +```php +$path = $request->photo->path(); + +$extension = $request->photo->extension(); +``` + +Store uploaded file with a randomly generated filename +```php +// path where the file should be stored relative to +// the filesystem's configured root directory +$path = $request->photo->store('images'); + +// optional 2nd param to specify the filesystem disk +$path = $request->photo->store('images', 's3'); +``` +Store uploaded file and specify the name +```php +$path = $request->photo->storeAs('images', 'filename.jpg'); + +$path = $request->photo->storeAs('images', 'filename.jpg', 's3'); +``` +See More: [File Storage](https://laravel.com/docs/8.x/filesystem) +Views {.cols-3} +--------------- +Presentational logic and HTML. +Create a view by placing a file with the `.blade.php` +extension in the `resources/views` directory. +```html + + + + +

Hello, {{ $name }}

+ + +``` + +Return a view from a route with the `view()` helper +```php +Route::get('/', function () { + return view('greeting', ['name' => 'James']); +}); +``` +See [Routing](#routing-cols-4) +See [Helpers](#helpers-cols-3) @@ -850,7 +730,3 @@ Also see - [Laravel Docs](https://laravel.com/docs/8.x) - [Laracasts](https://laracasts.com/) - [Laravel API](https://laravel.com/api/8.x/) - - - - From bfc98a6357c27fb9b0f32fd5a3aaf351a94b3fb7 Mon Sep 17 00:00:00 2001 From: jessinthecloud Date: Tue, 16 Nov 2021 21:12:16 -0500 Subject: [PATCH 12/14] add the rest of the basics --- laravel.md | 649 ++++++++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 647 insertions(+), 2 deletions(-) diff --git a/laravel.md b/laravel.md index 305eacb..ac5fad2 100644 --- a/laravel.md +++ b/laravel.md @@ -393,16 +393,67 @@ $url = route('profile', ['id' => 1, 'photos'=>'yes']); // /user/1/profile?photos=yes ``` +#### Eloquent Models +You may pass Eloquent models as parameter values. The +route helper will automatically extract the model's route key +```php +echo route('post.show', ['post' => $post]); +``` #### Redirects ```php // Generating Redirects... return redirect()->route('profile'); ``` +### URL Generation +Generate arbitrary URLs for your application that will +automatically use the scheme (HTTP or HTTPS) and host +from the current request +```php +$post = App\Models\Post::find(1); + +echo url("/posts/{$post->id}"); + +// http://example.com/posts/1 +``` +#### Current URL +```php +// Get the current URL without the query string... +echo url()->current(); + +// Get the current URL including the query string... +echo url()->full(); + +// Get the full URL for the previous request... +echo url()->previous(); +``` +### Named Route URL +See [Named Route](#named-route) + +### Error Handling +Report an exception but continue handling the current request +```php +public function isValid($value) +{ + try { + // Validate the value... + } catch (Throwable $e) { + report($e); + + return false; + } +} +``` + ### HTTP Exceptions + Generate an HTTP exception response using status code + ```php + // page not found + abort(404); + ``` + Controllers {.cols-3} --------------- - ### Basic ```php namespace App\Http\Controllers; @@ -707,11 +758,12 @@ extension in the `resources/views` directory. -

Hello, {{ $name }}

+

Hello,

``` +### view() helper Return a view from a route with the `view()` helper ```php Route::get('/', function () { @@ -721,7 +773,600 @@ Route::get('/', function () { See [Routing](#routing-cols-4) See [Helpers](#helpers-cols-3) +### Subdirectories +```php +// resources/views/admin.profile.blade.php +return view('admin.profile'); +``` +## Pass Data to Views +#### As an array +```php +return view('greetings', ['name' => 'Victoria']); +``` +#### Using with() +```php +return view('greeting') + ->with('name', 'Victoria') + ->with('occupation', 'Astronaut'); +``` +Access each value using the data's keys +```html + + +

Hello, {{ $name }}

+ +

Hello,

+ + +``` + +Blade Templating Engine {.cols-3} +--------------- +Blade is the templating engine included in Laravel +that also allows you to use plain PHP. + +### Views +Blade views are returned using the `view()` helper +```php +Route::get('/', function () { + return view('welcome', ['name' => 'Samantha']); +}); +``` +[See Views](#view-helper) + +### Displaying Data +Blade's echo statements `{{ }}` are automatically sent through +PHP's `htmlspecialchars` function to prevent XSS attacks. + +Display the contents of the name variable: +```html +Hello, {{ $name }}. +``` +Display results of a PHP function: +```html +The current UNIX timestamp is {{ time() }}. +``` +Display data without escaping with `htmlspecialchars` +```html +Hello, {!! $name !!}. +``` + +### Comments +```html +{{-- This comment will not be present in the rendered HTML --}} +``` + +### Directives {.cols-2} +#### if Statements +```php +@if (count($records) === 1) + I have one record! +@elseif (count($records) > 1) + I have multiple records! +@else + I don't have any records! +@endif +``` +#### isset & empty +```php +@isset($records) + // $records is defined and is not null... +@endisset + +@empty($records) + // $records is "empty"... +@endempty +``` +#### Authentication +```php +@auth + // The user is authenticated... +@endauth + +@guest + // The user is not authenticated... +@endguest +``` +#### Loops +```html +@for ($i = 0; $i < 10; $i++) + The current value is {{ $i }} +@endfor + +@foreach ($users as $user) +

This is user {{ $user->id }}

+@endforeach + +@forelse ($users as $user) +
  • {{ $user->name }}
  • +@empty +

    No users

    +@endforelse + +@while (true) +

    I'm looping forever.

    +@endwhile +``` +Loop Iteration: +```php +@foreach ($users as $user) + @if ($loop->first) + This is the first iteration. + @endif + + @if ($loop->last) + This is the last iteration. + @endif + +

    This is user {{ $user->id }}

    +@endforeach +``` +[See more](https://laravel.com/docs/8.x/blade#the-loop-variable) + +### Including Subviews +Include a Blade view from within another view. All variables that +are available to the parent view are also available to the included view +```html +
    + + @include('shared.errors') + +
    + +
    +
    +``` + +### Raw PHP +Execute a block of plain PHP +```php +@php + $counter = 1; +@endphp +``` + +### Stacks +Blade allows you to push to named stacks which can be rendered in another view or layout. +Useful for javascript libraries required by child views +```html + +@push('scripts') + +@endpush +``` +Render the stack +```html + + + + @stack('scripts') + +``` +Prepend to the beginning of a stack +```php +@push('scripts') + This will be second... +@endpush + +// Later... + +@prepend('scripts') + This will be first... +@endprepend +``` + + + + +Forms {.cols-3} +--------------- +### CSRF Field +Include a hidden CSRF token field to validate the request +```html +
    + @csrf + + ... +
    +``` + +### Method Field +Since HTML forms can't make `PUT`, `PATCH`, or `DELETE` requests, you +will need to add a hidden `_method` field to spoof these HTTP verbs: +```html +
    + @method('PUT') + + ... +
    +``` + +### Validation Errors +```html + + + + + + +@error('title') +
    {{ $message }}
    +@enderror +``` +[See Validation](#validation) + +### Repopulating Forms +When redirecting due to a validation error, request input is flashed to the session. +Retrieve the input from the previous request with the `old()` method +```php +$title = $request->old('title'); +``` +Or the `old()` helper +```html + +``` + +Validation {.cols-3} +--------------- +If validation fails, a redirect response to the previous URL will be generated. +If the incoming request is an XHR request, a JSON response with the +validation error messages will be returned. + +### Logic +```php +// in routes/web.php +Route::get('/post/create', [App\Http\Controllers\PostController::class, 'create']); +Route::post('/post', [App\Http\Controllers\PostController::class, 'store']); + +// in blog PostController... +public function store(Request $request) +{ + $validated = $request->validate([ + // input name => validation rules + 'title' => 'required|unique:posts|max:255', + 'body' => 'required', + ]); + + // The blog post is valid... +} +``` + +### Rules {.cols-3} +Can also be passed as an array +```php +$validatedData = $request->validate([ + 'title' => ['required', 'unique:posts', 'max:255'], + 'body' => ['required'], +]); +``` +#### after:date +Field must be a value after a given date. +```php +'start_date' => 'required|date|after:tomorrow' +``` +Instead of a date string, you may specify another field to compare against the date +```php +'finish_date' => 'required|date|after:start_date' +``` +See [before:date](#beforedate) +#### after_or_equal:date +Field must be a value after or equal to the given date. +See [after:date](#afterdate) +#### before:date +Field must be a value preceding the given date. +The name of another field may be supplied as the value of `date`. +See [after:date](#afterdate) +#### alpha_num +Field must be entirely alpha-numeric characters +#### boolean +Field must be able to be cast as a `boolean`. +Accepted input are `true`, `false`, `1`, `0`, `"1"`, and `"0"` +#### confirmed +Field must have a matching field of `{field}_confirmation`. +For example, if the field is password, a matching `password_confirmation` field must be present +#### date +Field must be a valid, non-relative date according to the `strtotime` PHP function. +#### current_password +Field must match the authenticated user's password. +#### email +Field must be formatted as an email address. +#### file +Field must be a successfully uploaded file. +#### max:value +Field must be less than or equal to a maximum value. +Strings, numerics, arrays, and files are evaluated like the [size](#sizevalue) rule. +#### min:value +Field must have a minimum value. +Strings, numerics, arrays, and files are evaluated like the [size](#sizevalue) rule. +#### mimetypes:text/plain,... +File must match one of the given MIME types: +```php +'video' => 'mimetypes:video/avi,video/mpeg,video/quicktime' +```` +_File's contents will be read and the framework will attempt to guess the +MIME type, regardless of the client's provided MIME type._ +#### mimes:foo,bar,... +Field must have a MIME type corresponding to one of the listed extensions. +```php +'photo' => 'mimes:jpg,bmp,png' +```` +_File's contents will be read and the framework will attempt to guess the +MIME type, regardless of the client's provided MIME type._ +[Full listing of MIME types & extensions](https://svn.apache.org/repos/asf/httpd/httpd/trunk/docs/conf/mime.types) +#### nullable +Field may be null. +#### numeric +Field must be numeric. +#### password +Field must match the authenticated user's password. +#### prohibited +Field must be empty or not present. +#### prohibited_if:anotherfield,value,... +Field must be empty or not present if the +_anotherfield_ field is equal to any value. +#### prohibited_unless:anotherfield,value,... +Field must be empty or not present unless the +_anotherfield_ field is equal to any value. +#### required +Field must be present in the input data and not empty. +A field is considered "empty" if one of the following conditions are true: +- The value is null. +- The value is an empty string. +- The value is an empty array or empty Countable object. +- The value is an uploaded file with no path. +#### required_with:foo,bar,... +Field must be present and not empty, only if any of the other +specified fields are present and not empty +#### size:value +Field must have a size matching the given value. +- For strings: number of characters +- For numeric data: integer value (must also have the `numeric` or `integer` rule). +- For arrays: count of the array +- For files: file size in kilobytes +```php +// Validate that a string is exactly 12 characters long... +'title' => 'size:12'; +// Validate that a provided integer equals 10... +'seats' => 'integer|size:10'; +// Validate that an array has exactly 5 elements... +'tags' => 'array|size:5'; +// Validate that an uploaded file is exactly 512 kilobytes... +'image' => 'file|size:512'; +``` +#### unique:table,column +Field must not exist within the given database table +#### url +Field must be a valid URL + +[See all available rules](https://laravel.com/docs/8.x/validation#available-validation-rules) + +### Validate Passwords +Ensure passwords have an adequate level of complexity +```php +$validatedData = $request->validate([ + 'password' => ['required', 'confirmed', Password::min(8)], +]); +``` +Password rule object allows you to easily customize the password complexity requirements +```php +// Require at least 8 characters... +Password::min(8) + +// Require at least one letter... +Password::min(8)->letters() + +// Require at least one uppercase and one lowercase letter... +Password::min(8)->mixedCase() + +// Require at least one number... +Password::min(8)->numbers() + +// Require at least one symbol... +Password::min(8)->symbols() +``` +Ensure a password has not been compromised in a public password data breach leak +_uses the [k-Anonymity](https://en.wikipedia.org/wiki/K-anonymity) model via the [haveibeenpwned.com](https://haveibeenpwned.com) service without sacrificing the user's privacy or security_ +```php +Password::min(8)->uncompromised() +``` +Methods can be chained +```php +Password::min(8) + ->letters() + ->mixedCase() + ->numbers() + ->symbols() + ->uncompromised() +``` +### Display Validation Errors +```php + + +

    Create Post

    + +@if ($errors->any()) +
    +
      + @foreach ($errors->all() as $error) +
    • {{ $error }}
    • + @endforeach +
    +
    +@endif + + +``` +See also [Display Errors](#display-errors) + +### Optional Fields +You will often need to mark your "optional" request fields as `nullable` +if you do not want the validator to consider `null` values as invalid +```php +// publish_at field may be either null or a valid date representation +$request->validate([ + 'title' => 'required|unique:posts|max:255', + 'body' => 'required', + 'publish_at' => 'nullable|date', +]); +``` + +### Validated Input +Retrieve the request data that underwent validation +```php +$validated = $request->validated(); +``` +Or with `safe()`, which returns an instance of `Illuminate\Support\ValidatedInput` +```php +$validated = $request->safe()->only(['name', 'email']); + +$validated = $request->safe()->except(['name', 'email']); + +$validated = $request->safe()->all(); +``` +```php +// Validated data may be iterated... +foreach ($request->safe() as $key => $value) { + // +} + +// Validated data may be accessed as an array... +$validated = $request->safe(); + +$email = $validated['email']; +``` + + + +Session {.cols-3} +--------------- +Laravel ships with a variety of session backends that are accessed through +a unified API. Memcached, Redis, and database support is included. + +### Configuration +Session configuration is in `config/session.php`. By default, +Laravel is configured to use the file session driver + +### Retrieving Data {.cols-2} +##### Via Request +```php +// ... +class UserController extends Controller +{ + public function show(Request $request, $id) + { + $value = $request->session()->get('key'); + + // + } +} +``` +Pass a default value as the second argument to use +if the key does not exist +```php +$value = $request->session()->get('key', 'default'); + +// closure can be passed and executed as default +$value = $request->session()->get('key', function () { + return 'default'; +}); +``` +#### Via session Helper +```php +Route::get('/home', function () { + // Retrieve a piece of data from the session... + $value = session('key'); + + // Specifying a default value... + $value = session('key', 'default'); + + // Store a piece of data in the session... + session(['key' => 'value']); +}); +``` +See [Session Helper]() +#### All Session Data +```php +$data = $request->session()->all(); +``` +#### Retrieve and Delete +Retrieve and delete an item from the session +```php +$value = $request->session()->pull('key', 'default'); +``` + +### Check Isset / Exists +Returns `true` if the item is present and is not `null`: +```php +if ($request->session()->has('users')) { + // +} +``` +Returns `true` if present, even if it's `null`: +```php +if ($request->session()->exists('users')) { + // +} +``` +Returns `true` if the item is `null` or is not present: +```php +if ($request->session()->missing('users')) { + // +} +``` +### Store Data +```php +// Via a request instance... +$request->session()->put('key', 'value'); + +// Via the global "session" helper... +session(['key' => 'value']); +``` +Push a new value onto a session value that is an array +```php +// array of team names +$request->session()->push('user.teams', 'developers'); +``` + + +Logging {.cols-3} +--------------- +### Configuration +Configuration options for logging behavior is in `config/logging.php`. +By default, Laravel will use the stack channel when logging messages, +which is used to aggregate multiple log channels into a single channel. + +### Levels +Offers all the log levels defined in the [RFC 5424 specification](https://tools.ietf.org/html/rfc5424): +- emergency +- alert +- critical +- error +- warning +- notice +- info +- debug + +### Log Facade +```php +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); +``` + +### Contextual Info +```php +use Illuminate\Support\Facades\Log; + +Log::info('User failed to login.', ['id' => $user->id]); +``` Also see From 4991458adce4ccca08b45730fbf12d5b34766f01 Mon Sep 17 00:00:00 2001 From: jessinthecloud Date: Tue, 16 Nov 2021 21:19:47 -0500 Subject: [PATCH 13/14] add deployment --- laravel.md | 37 ++++++++++++++++++++++++++++++++++++- 1 file changed, 36 insertions(+), 1 deletion(-) diff --git a/laravel.md b/laravel.md index ac5fad2..17bbb0d 100644 --- a/laravel.md +++ b/laravel.md @@ -19,7 +19,6 @@ intro: | Getting started {.cols-3} --------------- - ### Requirements #### PHP - PHP version >= 7.3 @@ -1369,6 +1368,42 @@ Log::info('User failed to login.', ['id' => $user->id]); ``` +Deployment {.cols-3} +--------------- +Ensure your web server directs all requests to your application's `public/index.php` file + +### Optimization +#### Composer's autoloader map +```bash +composer install --optimize-autoloader --no-dev +``` +#### Configuration Loading +_Be sure that you are only calling the `env` function from within your configuration files. +Once the configuration has been cached, the `.env` file will not be loaded and all calls +to the `env` function for `.env` variables will return `null`_ +```bash +php artisan config:cache +``` +#### Route Loading +```bash +php artisan route:cache +``` +#### View Loading +```bash +php artisan view:cache +``` + +### Debug Mode +The debug option in your `config/app.php` determines how much information +about an error is actually displayed to the user. +By default, this option is set to the value of the `APP_DEBUG` environment +variable in your `.env` file. + +**In your production environment, this value should always be `false`. +If the `APP_DEBUG` variable is set to `true` in production, you risk exposing sensitive configuration values to end users.** + + + Also see ------- From cbe61b879b47efa958087bc1e2d5c2b1c4ba5094 Mon Sep 17 00:00:00 2001 From: jessinthecloud Date: Tue, 16 Nov 2021 22:22:59 -0500 Subject: [PATCH 14/14] cleanup & typos Add doc links for each major heading --- laravel.md | 215 ++++++++++++++++++++++++++++++----------------------- 1 file changed, 124 insertions(+), 91 deletions(-) diff --git a/laravel.md b/laravel.md index 17bbb0d..43f0986 100644 --- a/laravel.md +++ b/laravel.md @@ -18,6 +18,7 @@ intro: | Getting started {.cols-3} --------------- +[Laravel Docs - Getting Started](https://laravel.com/docs/8.x/installation#your-first-laravel-project) ### Requirements #### PHP @@ -84,11 +85,14 @@ Access application via http://localhost Configuration {.cols-3} --------------- - +[Laravel Docs - Configuration](https://laravel.com/docs/8.x/configuration) ### .env {.cols-2} Retrieve values from `.env` file ```php +env('APP_DEBUG'); + +// with default value env('APP_DEBUG', false); ``` Determine current environment @@ -111,14 +115,14 @@ config(['app.timezone' => 'America/Chicago']); ``` ### Debug Mode -On (local dev): +Turn on (local dev): ```php // .env file APP_ENV=local APP_DEBUG=true // ... ``` -Off (production): +Turn off (production): ```php // .env file APP_ENV=production @@ -131,11 +135,13 @@ Temporarily disable application (503 status code) ```bash php artisan down ``` + #### Bypass Maintenance Mode ```bash php artisan down --secret="1630542a-246b-4b66-afa1-dd72a4c43515" ``` -``` +Visit your application URL `https://example.com/1630542a-246b-4b66-afa1-dd72a4c43515` to set a cookie and bypass the maintenance screen + #### Disable maintenance mode ```bash php artisan up @@ -143,11 +149,12 @@ php artisan up Routing {.cols-4} --------------- +[Laravel Docs - Basic Routing](https://laravel.com/docs/8.x/routing#basic-routing) -Web routes - `routes/web.php` -API routes - `routes/api.php` +Web routes: `routes/web.php` +API routes: `routes/api.php` -### Router Methods +### Router HTTP Methods ```php Route::get($uri, $callback); Route::post($uri, $callback); @@ -167,7 +174,7 @@ Route::any('/', function () { }); ``` -### Basic +### Basic Definition ```php use Illuminate\Support\Facades\Route; @@ -194,7 +201,7 @@ Route::get('/users', function (Request $request) { ``` ### Redirect Routes -HTTP 302 status +HTTP `302` status ```php Route::redirect('/here', '/there'); ``` @@ -202,12 +209,14 @@ Set the status code ```php Route::redirect('/here', '/there', 301); ``` -Permanent 301 redirect +Permanent `301` redirect ```php Route::permanentRedirect('/here', '/there'); ``` ### View Routes +Route only needs to return a view. +First argument: URI, second argument: view name ```php Route::view('/welcome', 'welcome'); @@ -216,6 +225,7 @@ Route::view('/welcome', 'welcome', ['name' => 'Taylor']); ``` ### Route Parameters {.cols-2} +Capture segments of the URI within your route #### Required parameters ```php Route::get('/user/{id}', function ($id) { @@ -262,8 +272,7 @@ Route::get('/user/profile', function () { // })->name('profile'); ``` -See: [Helpers](#helpers) - +See: [Helpers](#helpers-cols-3) ### Route Groups {.cols-2} Share attributes across routes @@ -371,6 +380,8 @@ $action = Route::currentRouteAction(); // string Helpers {.cols-3} --------------- +[Laravel Docs - Helpers](https://laravel.com/docs/8.x/helpers) + ### routes #### Named route ```php @@ -403,6 +414,7 @@ echo route('post.show', ['post' => $post]); // Generating Redirects... return redirect()->route('profile'); ``` +See [Routing](#routing-cols-4) ### URL Generation Generate arbitrary URLs for your application that will @@ -427,6 +439,9 @@ echo url()->full(); echo url()->previous(); ``` ### Named Route URL +```php +$url = route('profile'); +``` See [Named Route](#named-route) ### Error Handling @@ -453,6 +468,8 @@ public function isValid($value) Controllers {.cols-3} --------------- +[Laravel Docs - Controllers](https://laravel.com/docs/8.x/controllers) + ### Basic ```php namespace App\Http\Controllers; @@ -470,18 +487,19 @@ class UserController extends Controller } } ``` -Define a route to this controller method: +Define a route for this controller method: ```php use App\Http\Controllers\UserController; Route::get('/user/{id}', [UserController::class, 'show']); ``` - Requests {.cols-3} --------------- +[Laravel Docs - HTTP Requests](https://laravel.com/docs/8.x/requests) + ### CSRF Protection -Laravel automatically generates a CSRF "token" for each active user session. +Laravel automatically generates a CSRF "token" for each active user session. This token is used to verify that the authenticated user is the person actually making the requests. Get current session's token: @@ -494,7 +512,7 @@ Route::get('/token', function (Request $request) { // ... }); ``` -POST, PUT, PATCH, or DELETE forms should include a hidden CSRF `_token` field +`POST`, `PUT`, `PATCH`, or `DELETE` forms should include a hidden CSRF `_token` field in the form to validate the request. ```html
    @@ -504,13 +522,14 @@ in the form to validate the request.
    ``` +See [Forms](#forms-cols-3) ### Accessing Request Get an instance of the current request by type-hinting the controller action or route closure ```php // controller action -class UaerController extends Controller +class UserController extends Controller { public function store(Request $request) { @@ -530,7 +549,7 @@ The request's path information ```php $uri = $request->path(); -// http://example.com/foo/bar --> foo/bar +// https://example.com/foo/bar --> foo/bar ``` #### Match path to pattern Verify that the incoming request path matches a given pattern @@ -546,12 +565,14 @@ if ($request->routeIs('admin.*')) { // } ``` -#### URL + +### URL Full URL for the incoming request ```php // URL without the query string $url = $request->url(); +// URL including query string $urlWithQueryString = $request->fullUrl(); // append data to query string @@ -599,16 +620,7 @@ if ($request->accepts(['text/html', 'application/json'])) { // ... } ``` -Determine content type is most preferred by the request -```php -$preferred = $request->prefers(['text/html', 'application/json']); -``` -Shortcut to determine if the incoming request expects a JSON response -```php -if ($request->expectsJson()) { - // ... -} -``` + ### Input Retrieve all the incoming request's input data as an array @@ -624,7 +636,7 @@ $request->collect('users')->each(function ($user) { // ... }); ``` -[See helpers](#helpers) +See [Helpers](#helpers-cols-3) Retrieve user input (also gets values from query string) ```php @@ -661,14 +673,15 @@ $query = $request->query(); #### Boolean Input Values Helpful for checkbox inputs or other booleans. -Return `true` for 1, "1", true, "true", "on", and "yes". +Return `true` for `1`, `"1"`, `true`, `"true"`, `"on"`, and `"yes"`. All other values will return `false` ```php $archived = $request->boolean('archived'); ``` ### Dynamic Properties -Access inputs via properties. If not found as an input, the route parameters will be checked. +Access inputs via properties. +If not found as an input, the route parameters will be checked. ```php $name = $request->name; ``` @@ -711,7 +724,8 @@ Or use the `old()` helper ```php ``` -See: (Helpers)[#helpers] +See: [Helpers](#helpers-cols-3) +See: [Forms](#forms-cols-3) ### Uploaded Files Retrieve uploaded file from request @@ -743,13 +757,14 @@ $path = $request->photo->storeAs('images', 'filename.jpg'); $path = $request->photo->storeAs('images', 'filename.jpg', 's3'); ``` -See More: [File Storage](https://laravel.com/docs/8.x/filesystem) - +See More: [Laravel File Storage](https://laravel.com/docs/8.x/filesystem) Views {.cols-3} --------------- -Presentational logic and HTML. +[Laravel Docs - Views](https://laravel.com/docs/8.x/views) + +Presentational logic and HTML. Create a view by placing a file with the `.blade.php` extension in the `resources/views` directory. ```html @@ -762,14 +777,14 @@ extension in the `resources/views` directory. ``` -### view() helper +### view helper Return a view from a route with the `view()` helper ```php Route::get('/', function () { return view('greeting', ['name' => 'James']); }); ``` -See [Routing](#routing-cols-4) +See [View Routes](#view-routes) See [Helpers](#helpers-cols-3) ### Subdirectories @@ -777,7 +792,7 @@ See [Helpers](#helpers-cols-3) // resources/views/admin.profile.blade.php return view('admin.profile'); ``` -## Pass Data to Views +### Pass Data to Views #### As an array ```php return view('greetings', ['name' => 'Victoria']); @@ -800,8 +815,10 @@ Access each value using the data's keys ``` -Blade Templating Engine {.cols-3} +Blade Templates {.cols-3} --------------- +[Laravel Docs - Blade Templates](https://laravel.com/docs/8.x/blade) + Blade is the templating engine included in Laravel that also allows you to use plain PHP. @@ -812,7 +829,12 @@ Route::get('/', function () { return view('welcome', ['name' => 'Samantha']); }); ``` -[See Views](#view-helper) +See: [Views](#view-helper) + +### Comments +```html +{{-- This comment will not be present in the rendered HTML --}} +``` ### Displaying Data Blade's echo statements `{{ }}` are automatically sent through @@ -831,11 +853,6 @@ Display data without escaping with `htmlspecialchars` Hello, {!! $name !!}. ``` -### Comments -```html -{{-- This comment will not be present in the rendered HTML --}} -``` - ### Directives {.cols-2} #### if Statements ```php @@ -901,11 +918,11 @@ Loop Iteration:

    This is user {{ $user->id }}

    @endforeach ``` -[See more](https://laravel.com/docs/8.x/blade#the-loop-variable) +See more: [Laravel Loop Variable](https://laravel.com/docs/8.x/blade#the-loop-variable) ### Including Subviews -Include a Blade view from within another view. All variables that -are available to the parent view are also available to the included view +Include a Blade view from within another view. +All variables that are available to the parent view are also available to the included view ```html
    @@ -926,7 +943,7 @@ Execute a block of plain PHP ``` ### Stacks -Blade allows you to push to named stacks which can be rendered in another view or layout. +Blade allows you to push to named stacks which can be rendered in another view or layout. Useful for javascript libraries required by child views ```html @@ -956,10 +973,10 @@ Prepend to the beginning of a stack ``` - - Forms {.cols-3} --------------- +[Laravel Docs - Forms](https://laravel.com/docs/8.x/blade#forms) + ### CSRF Field Include a hidden CSRF token field to validate the request ```html @@ -969,6 +986,7 @@ Include a hidden CSRF token field to validate the request ... ``` +See: [CSRF Protection](#csrf-protection) ### Method Field Since HTML forms can't make `PUT`, `PATCH`, or `DELETE` requests, you @@ -993,11 +1011,11 @@ will need to add a hidden `_method` field to spoof these HTTP verbs:
    {{ $message }}
    @enderror ``` -[See Validation](#validation) +See: [Validation](#validation-cols-3) ### Repopulating Forms -When redirecting due to a validation error, request input is flashed to the session. -Retrieve the input from the previous request with the `old()` method +When redirecting due to a validation error, request input is flashed to the session. +Retrieve the input from the previous request with the `old` method ```php $title = $request->old('title'); ``` @@ -1008,7 +1026,9 @@ Or the `old()` helper Validation {.cols-3} --------------- -If validation fails, a redirect response to the previous URL will be generated. +[Laravel Docs - Validation](https://laravel.com/docs/8.x/validation) + +If validation fails, a redirect response to the previous URL will be generated. If the incoming request is an XHR request, a JSON response with the validation error messages will be returned. @@ -1018,7 +1038,7 @@ validation error messages will be returned. Route::get('/post/create', [App\Http\Controllers\PostController::class, 'create']); Route::post('/post', [App\Http\Controllers\PostController::class, 'store']); -// in blog PostController... +// in app/Http/Controllers/PostController... public function store(Request $request) { $validated = $request->validate([ @@ -1032,6 +1052,8 @@ public function store(Request $request) ``` ### Rules {.cols-3} +[See all available rules](https://laravel.com/docs/8.x/validation#available-validation-rules) + Can also be passed as an array ```php $validatedData = $request->validate([ @@ -1054,7 +1076,7 @@ Field must be a value after or equal to the given date. See [after:date](#afterdate) #### before:date Field must be a value preceding the given date. -The name of another field may be supplied as the value of `date`. +The name of another field may be supplied as the value of `date`. See [after:date](#afterdate) #### alpha_num Field must be entirely alpha-numeric characters @@ -1064,34 +1086,36 @@ Accepted input are `true`, `false`, `1`, `0`, `"1"`, and `"0"` #### confirmed Field must have a matching field of `{field}_confirmation`. For example, if the field is password, a matching `password_confirmation` field must be present -#### date -Field must be a valid, non-relative date according to the `strtotime` PHP function. #### current_password Field must match the authenticated user's password. +#### date +Field must be a valid, non-relative date according to the `strtotime` PHP function. #### email Field must be formatted as an email address. #### file -Field must be a successfully uploaded file. +Field must be a successfully uploaded file. +See: [Uploaded Files](#uploaded-files) #### max:value -Field must be less than or equal to a maximum value. +Field must be less than or equal to a maximum value. Strings, numerics, arrays, and files are evaluated like the [size](#sizevalue) rule. #### min:value -Field must have a minimum value. +Field must have a minimum value. Strings, numerics, arrays, and files are evaluated like the [size](#sizevalue) rule. #### mimetypes:text/plain,... File must match one of the given MIME types: ```php 'video' => 'mimetypes:video/avi,video/mpeg,video/quicktime' ```` -_File's contents will be read and the framework will attempt to guess the +> _File's contents will be read and the framework will attempt to guess the MIME type, regardless of the client's provided MIME type._ #### mimes:foo,bar,... Field must have a MIME type corresponding to one of the listed extensions. ```php 'photo' => 'mimes:jpg,bmp,png' ```` -_File's contents will be read and the framework will attempt to guess the -MIME type, regardless of the client's provided MIME type._ +> _File's contents will be read and the framework will attempt to guess the +MIME type, regardless of the client's provided MIME type._ + [Full listing of MIME types & extensions](https://svn.apache.org/repos/asf/httpd/httpd/trunk/docs/conf/mime.types) #### nullable Field may be null. @@ -1110,9 +1134,9 @@ _anotherfield_ field is equal to any value. #### required Field must be present in the input data and not empty. A field is considered "empty" if one of the following conditions are true: -- The value is null. +- The value is `null`. - The value is an empty string. -- The value is an empty array or empty Countable object. +- The value is an empty array or empty `Countable` object. - The value is an uploaded file with no path. #### required_with:foo,bar,... Field must be present and not empty, only if any of the other @@ -1147,7 +1171,7 @@ $validatedData = $request->validate([ 'password' => ['required', 'confirmed', Password::min(8)], ]); ``` -Password rule object allows you to easily customize the password complexity requirements +`Password` rule object allows you to easily customize the password complexity requirements ```php // Require at least 8 characters... Password::min(8) @@ -1165,10 +1189,11 @@ Password::min(8)->numbers() Password::min(8)->symbols() ``` Ensure a password has not been compromised in a public password data breach leak -_uses the [k-Anonymity](https://en.wikipedia.org/wiki/K-anonymity) model via the [haveibeenpwned.com](https://haveibeenpwned.com) service without sacrificing the user's privacy or security_ ```php Password::min(8)->uncompromised() ``` +> _Uses the [k-Anonymity](https://en.wikipedia.org/wiki/K-anonymity) model via the [haveibeenpwned.com](https://haveibeenpwned.com) service without sacrificing the user's privacy or security_ + Methods can be chained ```php Password::min(8) @@ -1196,7 +1221,7 @@ Password::min(8) ``` -See also [Display Errors](#display-errors) +See: [Validation Errors](#validation-errors) ### Optional Fields You will often need to mark your "optional" request fields as `nullable` @@ -1223,28 +1248,30 @@ $validated = $request->safe()->except(['name', 'email']); $validated = $request->safe()->all(); ``` +#### Iterate ```php -// Validated data may be iterated... foreach ($request->safe() as $key => $value) { // } - -// Validated data may be accessed as an array... +``` +#### Access as an array +```php $validated = $request->safe(); $email = $validated['email']; ``` - Session {.cols-3} --------------- +[Laravel Docs - Session](https://laravel.com/docs/8.x/session) + Laravel ships with a variety of session backends that are accessed through a unified API. Memcached, Redis, and database support is included. ### Configuration -Session configuration is in `config/session.php`. By default, -Laravel is configured to use the file session driver +Session configuration is in `config/session.php`. +By default, Laravel is configured to use the file session driver ### Retrieving Data {.cols-2} ##### Via Request @@ -1265,12 +1292,12 @@ if the key does not exist ```php $value = $request->session()->get('key', 'default'); -// closure can be passed and executed as default +// closure can be passed and executed as a default $value = $request->session()->get('key', function () { return 'default'; }); ``` -#### Via session Helper +#### Via session helper ```php Route::get('/home', function () { // Retrieve a piece of data from the session... @@ -1283,7 +1310,8 @@ Route::get('/home', function () { session(['key' => 'value']); }); ``` -See [Session Helper]() +See: [Session Helper]() + #### All Session Data ```php $data = $request->session()->all(); @@ -1314,11 +1342,12 @@ if ($request->session()->missing('users')) { } ``` ### Store Data +Via a request instance ```php -// Via a request instance... $request->session()->put('key', 'value'); - -// Via the global "session" helper... +``` +Via the global "session" helper +```php session(['key' => 'value']); ``` Push a new value onto a session value that is an array @@ -1330,13 +1359,16 @@ $request->session()->push('user.teams', 'developers'); Logging {.cols-3} --------------- +[Laravel Docs - Logging](https://laravel.com/docs/8.x/logging) + +> Laravel utilizes the [Monolog](https://github.com/Seldaek/monolog) library + ### Configuration Configuration options for logging behavior is in `config/logging.php`. -By default, Laravel will use the stack channel when logging messages, -which is used to aggregate multiple log channels into a single channel. +By default, Laravel will use the stack channel when logging messages, which aggregates multiple log channels into a single channel. ### Levels -Offers all the log levels defined in the [RFC 5424 specification](https://tools.ietf.org/html/rfc5424): +All the log levels defined in the [RFC 5424 specification](https://tools.ietf.org/html/rfc5424) are available: - emergency - alert - critical @@ -1370,6 +1402,8 @@ Log::info('User failed to login.', ['id' => $user->id]); Deployment {.cols-3} --------------- +[Laravel Docs - Deployment](https://laravel.com/docs/8.x/deployment) + Ensure your web server directs all requests to your application's `public/index.php` file ### Optimization @@ -1378,9 +1412,9 @@ Ensure your web server directs all requests to your application's `public/index. composer install --optimize-autoloader --no-dev ``` #### Configuration Loading -_Be sure that you are only calling the `env` function from within your configuration files. +**_Be sure that you are only calling the `env` function from within your configuration files. Once the configuration has been cached, the `.env` file will not be loaded and all calls -to the `env` function for `.env` variables will return `null`_ +to the `env` function for `.env` variables will return `null`_** ```bash php artisan config:cache ``` @@ -1399,14 +1433,13 @@ about an error is actually displayed to the user. By default, this option is set to the value of the `APP_DEBUG` environment variable in your `.env` file. -**In your production environment, this value should always be `false`. -If the `APP_DEBUG` variable is set to `true` in production, you risk exposing sensitive configuration values to end users.** +_**In your production environment, this value should always be `false`. +If the `APP_DEBUG` variable is set to `true` in production, you risk exposing sensitive configuration values to end users.**_ Also see ------- - - [Laravel Docs](https://laravel.com/docs/8.x) - [Laracasts](https://laracasts.com/) - [Laravel API](https://laravel.com/api/8.x/)