Laravel Cheat Sheet & Quick Reference
Laravel Cheat Sheet & Quick Reference
9k
Human Machine
Interface & Dive In
Intuitive Engineering
Laravel
Laravel is an expressive and progressive web application framework for PHP. This cheat sheet
provides a reference for common commands and features for Laravel 8.
Human Machine
Interface & Dive In
Intuitive Engineering
# Getting Started
Requirements
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
Ensure your web server directs all requests to your application's public/[Link] file, See:
Deployment
Windows
Install Docker Desktop
In WSL2 terminal:
In terminal:
$environment = App::environment();
- Debug Mode
Turn on (local dev):
// .env file
APP_ENV=local
APP_DEBUG=true
// ...
# Routing
Router HTTP 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);
Route::any('/', function () {
//
});
Basic Definition
use Illuminate\Support\Facades\Route;
// closure
Route::get('/greeting', function () {
return 'Hello World';
});
// controller action
Route::get(
'/user/profile',
[UserProfileController::class, 'show']
Dependency Injection
use Illuminate\Http\Request;
// with data
Route::view('/welcome', 'welcome', ['name' => 'Taylor']);
// Route definition...
Route::get('/users/{user}', [UserController::class, 'show']);
Convenient way to automatically inject the model instances directly into your routes
- Route Parameters
Capture segments of the URI within your route
Required parameters
Route::get('/user/{id}', function ($id) {
return 'User '.$id;
});
Optional Parameters
Route::get('/user/{name?}', function ($name = null) {
return $name;
});
- Redirect Routes
HTTP 302 status
Route::redirect('/here', '/there');
See: Helpers
Fallback Routes
Route::fallback(function () {
//
});
Route::get('/user/profile', function () {
// Uses first & second middleware...
});
});
URI Prefixes
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 "[Link]"...
})->name('users');
});
// Illuminate\Routing\Route
$route = Route::current();
// string
$name = Route::currentRouteName();
// string
$action = Route::currentRouteAction();
# Helpers
- routes
Named route
$url = route('profile');
With parameters
// Route::get('/user/{id}/profile', /*...*/ )->name('profile);
// /user/1/profile/
// /user/1/profile?photos=yes
Redirects
// Generating Redirects...
return redirect()->route('profile');
Eloquent Models
echo route('[Link]', ['post' => $post]);
The route helper will automatically extract the model's route key. See Routing
- URL Generation
Generate arbitrary URLs for your application that will automatically use the scheme (HTTP or
HTTPS) and host from the current request
$post = App\Models\Post::find(1);
echo url("/posts/{$post->id}");
// [Link]
Current URL
// Get the current URL without the query string...
echo url()->current();
return false;
}
}
# Controllers
Basic
namespace App\Http\Controllers;
use App\Http\Controllers\Controller;
use App\Models\User;
$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
See Forms
- Accessing Request
Get an instance of the current request by type-hinting the controller action or route closure
// controller action
class UserController extends Controller
{
public function store(Request $request)
{
$name = $request->input('name');
}
}
// closure
Route::get('/', function (Request $request) {
//
});
See Routing
- Path
The request's path information
$uri = $request->path();
- URL
Full URL for the incoming request
// URL without the query string
$url = $request->url();
Request Method
$method = $request->method();
Client IP
$ipAddress = $request->ip();
Headers
$value = $request->header('X-Header-Name');
- Content Type
Return an array containing all the content types accepted by the request
$contentTypes = $request->getAcceptableContentTypes();
- Input
Retrieve all the incoming request's input data as an array
$input = $request->all();
See Helpers
Retrieve user input (also gets values from query string)
$name = $request->input('name');
$names = $request->input('products.*.name');
- Dynamic Properties
Access inputs via properties.
If not found as an input, the route parameters will be checked.
$name = $request->name;
$input = $request->except(['credit_card']);
$input = $request->except('credit_card');
- Check Existence
Determine if value(s) present
if ($request->has('name')) {
//
}
- Old Input
Retrieve input from the previous request
$username = $request->old('username');
See: Helpers
See: Forms
- Uploaded Files
Retrieve uploaded file from request
$file = $request->file('photo');
$file = $request->photo;
$extension = $request->photo->extension();
# Views
Intro
Laravel Docs - Views
<!-- View stored in resources/views/[Link] -->
<html>
<body>
<h1>Hello, <?php echo $name; ?></h1>
</body>
</html>
Using with()
return view('greeting')
->with('name', 'Victoria')
->with('occupation', 'Astronaut');
- view helper
Return a view from a route with the view() helper
Route::get('/', function () {
return view('greeting', ['name' => 'James']);
});
# Blade Templates
Intro
Laravel Docs - Blade Templates
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
Route::get('/', function () {
return view('welcome', ['name' => 'Samantha']);
});
See: Views
Comments
{{-- This comment will not be present in the rendered HTML --}}
- Directives
if Statements
@if (count($records) === 1)
I have one record!
@elseif (count($records) > 1)
I have multiple records!
@else
I don't have any records!
@endif
@empty($records)
// $records is "empty"...
@endempty
Authentication
@auth
// The user is authenticated...
@endauth
@guest
// The user is not authenticated...
@endguest
Loops
@for ($i = 0; $i < 10; $i++)
The current value is {{ $i }}
@endfor
@while (true)
<p>I'm looping forever.</p>
@endwhile
Loop Iteration:
@foreach ($users as $user)
@if ($loop->first)
This is the first iteration.
@endif
@if ($loop->last)
This is the last iteration.
@endif
<form>
<!-- Form Contents -->
</form>
</div>
- Raw PHP
Execute a block of plain 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
<!-- Add to the stack -->
@push('scripts')
<script src="/[Link]"></script>
@endpush
@stack('scripts')
</head>
// Later...
@prepend('scripts')
# Forms
Intro
Laravel Docs - Forms
- CSRF Field
Include a hidden CSRF token field to validate the request
<form method="POST" action="/profile">
@csrf
...
</form>
Validation Errors
<!-- /resources/views/post/[Link] -->
@error('title')
<div class="alert alert-danger">{{ $message }}</div>
@enderror
See: 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
$title = $request->old('title');
# Validation
Intro
Laravel Docs - 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.
Logic
// in routes/[Link]
Route::get('/post/create', [App\Http\Controllers\PostController::class, 'cre
Route::post('/post', [App\Http\Controllers\PostController::class, 'store']);
// in app/Http/Controllers/PostController...
public function store(Request $request)
{
$validated = $request->validate([
// input name => validation rules
'title' => 'required|unique:posts|max:255',
'body' => 'required',
]);
- Rules
Can also be passed as an array
$validatedData = $request->validate([
'title' => ['required', 'unique:posts', 'max:255'],
'body' => ['required'],
]);
after:date
Field must be a value after a given date.
'start_date' => 'required|date|after:tomorrow'
Instead of a date string, you may specify another field to compare against the date
'finish_date' => 'required|date|after:start_date'
See before:date
after_or_equal:date
Field must be a value after or equal to the given date.
See after:date
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
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
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.
See: Uploaded Files
max:value
Field must be less than or equal to a maximum value.
Strings, numerics, arrays, and files are evaluated like the size rule.
min:value
Field must have a minimum value.
Strings, numerics, arrays, and files are evaluated like the size rule.
mimetypes:text/plain,...
File must match one of the given MIME types:
'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.
'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
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
// 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
- Validate Passwords
Ensure passwords have an adequate level of complexity
$validatedData = $request->validate([
'password' => ['required', 'confirmed', Password::min(8)],
]);
Password rule object allows you to easily customize the password complexity requirements
// Require at least 8 characters...
Password::min(8)
Ensure a password has not been compromised in a public password data breach leak
Password::min(8)->uncompromised()
Uses the k-Anonymity model via the [Link] service without sacrificing the user's privacy
or security
Methods can be chained
Password::min(8)
->letters()
->mixedCase()
->numbers()
->symbols()
<h1>Create Post</h1>
@if ($errors->any())
<div class="alert alert-danger">
<ul>
@foreach ($errors->all() as $error)
<li><!--swig13--></li>
@endforeach
</ul>
</div>
@endif
$validated = $request->safe()->all();
Iterate
foreach ($request->safe() as $key => $value) {
//
}
Access as an array
$validated = $request->safe();
$email = $validated['email'];
# Session
Intro
Laravel Docs - 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/[Link].
By default, Laravel is configured to use the file session driver
- Check Isset / Exists
Returns true if the item is present and is not null:
if ($request->session()->has('users')) {
//
}
- Retrieving Data
Via Request
// ...
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
$value = $request->session()->get('key', 'default');
- Store Data
Via a request instance
$request->session()->put('key', 'value');
#- Logging
Configuration
Configuration options for logging behavior is in config/[Link].
By default, Laravel will use the stack channel when logging messages, which aggregates multiple
- Levels
All the log levels defined in the RFC 5424 specification are available:
emergency
alert
critical
error
warning
notice
info
debug
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);
Contextual Info
use Illuminate\Support\Facades\Log;
# Deployment
Intro
Laravel Docs - Deployment
E b di ll li i ' bli /i d h fil
- Optimization
Composer's autoloader map
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
php artisan config:cache
Route Loading
php artisan route:cache
View Loading
php artisan view:cache
- Debug Mode
The debug option in your config/[Link] 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
Laravel Docs
Laracasts
Laravel API
Related Cheatsheet
CSS 3 Cheatsheet HTML Cheatsheet
Quick Reference Quick Reference
JavaScript Cheatsheet jQuery Cheatsheet
Quick Reference Quick Reference
Recent Cheatsheet
Remote Work Revolution Cheatsheet Homebrew Cheatsheet
Quick Reference Quick Reference
PyTorch Cheatsheet Taskset Cheatsheet
Quick Reference Quick Reference