16 KiB
title, date, icon, background, tags, categories, intro
| title | date | icon | background | tags | categories | intro | |||||
|---|---|---|---|---|---|---|---|---|---|---|---|
| Laravel | 2021-11-09 | bg-orange-500 |
|
|
[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
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
Installation
Local development with Docker Desktop and Sail
Windows
- Install & enable WSL2
- Install Docker Desktop
- Ensure that Docker Desktop is configured to use WSL2
- In WSL2 terminal:
curl -s https://laravel.build/example-app | bash
cd example-app
./vendor/bin/sail up
Mac
- Install Docker Desktop
- In terminal:
curl -s "https://laravel.build/example-app" | bash
cd example-app
./vendor/bin/sail up
Linux
curl -s https://laravel.build/example-app | bash
cd example-app
./vendor/bin/sail up
Installation via Composer
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
env('APP_DEBUG', false);
Determine current environment
use Illuminate\Support\Facades\App;
$environment = App::environment();
Accessing configuration values using "dot" syntax
// 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:
config(['app.timezone' => 'America/Chicago']);
Debug Mode
On (local dev):
// .env file
APP_ENV=local
APP_DEBUG=true
// ...
Off (production):
// .env file
APP_ENV=production
APP_DEBUG=false
// ...
Maintenance Mode
Temporarily disable application (503 status code)
php artisan down
Set Refresh HTTP header
// auto refresh browser after 60 seconds
php artisan down --refresh=15
Set Retry-After HTTP header
// retry after 60 seconds
php artisan down --retry=60
Bypass Maintenance Mode
php artisan down --secret="1630542a-246b-4b66-afa1-dd72a4c43515"
Pre-Render Maintenance View
php artisan down --render="errors::503"
Redirect instead of maintenance view
php artisan down --redirect=/
Disable maintenance mode
php artisan up
Customize maintenance template
resources/views/errors/503.blade.php
Routing
Web routes - routes/web.php
API routes - routes/api.php
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);
Multiple HTTP methods
Route::match(['get', 'post'], '/', function () {
//
});
Route::any('/', function () {
//
});
Basic
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
use Illuminate\Http\Request;
Route::get('/users', function (Request $request) {
// ...
});
Redirect Routes
HTTP 302 status
Route::redirect('/here', '/there');
Set the status code
Route::redirect('/here', '/there', 301);
Permanent 301 redirect
Route::permanentRedirect('/here', '/there');
View Routes
Route::view('/welcome', 'welcome');
// with data
Route::view('/welcome', 'welcome', ['name' => 'Taylor']);
Route Parameters
Required params
Route::get('/user/{id}', function ($id) {
return 'User '.$id;
});
With dependency injection
use Illuminate\Http\Request;
Route::get('/user/{id}', function (Request $request, $id) {
return 'User '.$id;
});
Optional Parameters
Route::get('/user/{name?}', function ($name = null) {
return $name;
});
Route::get('/user/{name?}', function ($name = 'John') {
return $name;
});
Regular Expression Constraints
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
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
// 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
Route::get('/user/profile', function () {
//
})->name('profile');
See: Helpers
Route Groups
Share attributes across routes
Middleware
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
Route::domain('{account}.example.com')->group(function () {
Route::get('user/{id}', function ($account, $id) {
//
});
});
Prefixes
URI prefix
Route::prefix('admin')->group(function () {
Route::get('/users', function () {
// Matches The "/admin/users" URL
});
});
Name Prefix
Route::name('admin.')->group(function () {
Route::get('/users', function () {
// Route assigned name "admin.users"...
})->name('users');
});
Route Model Binding
Convenient way to automatically inject the model instances directly into your routes
Implicit binding
With closure
use App\Models\User;
Route::get('/users/{user}', function (User $user) {
return $user->email;
});
// /user/1 --> User::where('id', '=', 1);
With controller action
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
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
// in App\Models\Post
public function getRouteKeyName()
{
return 'slug';
}
Multiple models - second is child of first
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
// 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
// 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
Route::fallback(function () {
//
});
Accessing current route
use Illuminate\Support\Facades\Route;
$route = Route::current(); // Illuminate\Routing\Route
$name = Route::currentRouteName(); // string
$action = Route::currentRouteAction(); // string
Helpers
routes
Named route
$url = route('profile');
With parameters
// Route::get('/user/{id}/profile', /*...*/ )->name('profile);
$url = route('profile', ['id' => 1]);
// /user/1/profile/
Additional parameters will be added to query string
// Route::get('/user/{id}/profile', /*...*/ )->name('profile);
$url = route('profile', ['id' => 1, 'photos'=>'yes']);
// /user/1/profile?photos=yes
Redirects
// Generating Redirects...
return redirect()->route('profile');
Controllers
Basic
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:
use App\Http\Controllers\UserController;
Route::get('/user/{id}', [UserController::class, 'show']);
Single Action
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:
use App\Http\Controllers\ProvisionServer;
Route::post('/server', ProvisionServer::class);
See: Artisan Commands
Requests
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:
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.
<form method="POST" action="/profile">
@csrf
<!-- Equivalent to... -->
<input type="hidden" name="_token" value="{{ csrf_token() }}" />
</form>
Exclude URIs From CSRF Protection
Define routes outside of the routes/web.php
Or
Adding route URIs to the $except property of VerifyCsrfToken
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
// controller action
class UaerController extends Controller
{
public function store(Request $request)
{
$name = $request->input('name');
}
}
// closure
Route::get('/', function (Request $request) {
//
});
Path
The request's path information
$uri = $request->path();
// http://example.com/foo/bar --> foo/bar
Match path to pattern
Verify that the incoming request path matches a given pattern
// * is wildcard
if ($request->is('admin/*')) {
//
}
Determine if the incoming request matches a named route
if ($request->routeIs('admin.*')) {
//
}
URL
Full URL for the incoming request
// URL without the query string
$url = $request->url();
$urlWithQueryString = $request->fullUrl();
// append data to query string
$request->fullUrlWithQuery(['type' => 'phone']);
Request Method
$method = $request->method();
// verify that the HTTP verb matches a given string
if ($request->isMethod('post')) {
//
}
Headers
$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
$ipAddress = $request->ip();
Content
Return an array containing all of the content types accepted by the request
$contentTypes = $request->getAcceptableContentTypes();
Boolean check for content types are accepted by the request
if ($request->accepts(['text/html', 'application/json'])) {
// ...
}
Determine content type is most preferred by the request
$preferred = $request->prefers(['text/html', 'application/json']);
Shortcut to determine if the incoming request expects a JSON response
if ($request->expectsJson()) {
// ...
}
Input
Retrieve all of the incoming request's input data as an array
$input = $request->all();
Retrieve all of the incoming request's input data as a collection
$input = $request->collect();
// retrieve subset as collection
$request->collect('users')->each(function ($user) {
// ...
});
Retrieve user input (also gets values from query string)
$name = $request->input('name');
// with default value if none present
$name = $request->input('name', 'Sally');
Access array inputs
$name = $request->input('products.0.name');
$names = $request->input('products.*.name');
Retrieve all of the input values as an associative array:
$input = $request->input();
Only retrieve values from the query string:
$name = $request->query('name');
// with default value
$name = $request->query('name', 'Helen');
Retrieve all of the query string values as an associative array:
$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
$archived = $request->boolean('archived');
Dynamic Properties
Access inputs via properties. If not found as an input, the route parameters will be checked.
$name = $request->name;
Retrieve Partial Input
$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
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
$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
if ($request->filled('name')) {
//
}
Execute if value present and not empty
$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
if ($request->missing('name')) {
//
}