Laravel Cheat Sheet & Quick Reference
Laravel Cheat Sheet & Quick Reference
Laravel Cheat Sheet & Quick Reference
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.
# Getting Started
Requirements
Windows
In WSL2 terminal:
A li i i h //l lh
Mac
In terminal:
# Configuration
.env
env('APP_DEBUG');
$environment = App::environment();
Debug Mode
// .env file
APP_ENV=local
APP_DEBUG=true
// ...
// .env file
APP_ENV=production
APP_DEBUG=false
// ...
Maintenance Mode
php artisan up
Bypass Maintenance Mode
Visit your application URL https://example.com/1630542a-246b-4b66-afa1-dd72a4c43515 to set a cookie and bypass the maintenance
screen
# 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::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;
View Routes
// with data
Route::view('/welcome', 'welcome', ['name' => 'Taylor']);
Implicit binding
With closure
use App\Models\User;
use App\Http\Controllers\UserController;
use App\Models\User;
// Route definition...
Route::get('/users/{user}', [UserController::class, 'show']);
use App\Models\Post;
// in App\Models\Post
public function getRouteKeyName()
{
return 'slug';
}
use App\Models\Post;
use App\Models\User;
Route::get('/users/{user}/posts/{post:slug}', function (User $user, Post $post) {
return $post;
});
Convenient way to automatically inject the model instances directly into your routes
Route Parameters
Required parameters
use Illuminate\Http\Request;
Optional Parameters
Redirect Routes
Route::redirect('/here', '/there');
Route::permanentRedirect('/here', '/there');
Route::get('/user/profile', function () {
//
})->name('profile');
See: Helpers
Fallback Routes
Route::fallback(function () {
//
});
Route Groups
Middleware
Route::middleware(['first', 'second'])->group(function () {
Route::get('/', function () {
// Uses first & second middleware...
});
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 "admin.users"...
})->name('users');
});
use Illuminate\Support\Facades\Route;
// Illuminate\Routing\Route
$route = Route::current();
// string
$name = Route::currentRouteName();
// string
$action = Route::currentRouteAction();
# Helpers
routes
Named route
$url = route('profile');
With parameters
// /user/1/profile/
With query string
// /user/1/profile?photos=yes
Redirects
// Generating Redirects...
return redirect()->route('profile');
Eloquent Models
echo route('post.show', ['post' => $post]);
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}");
// http://example.com/posts/1
Current URL
$url = route('profile');
Error Handling
public function isValid($value)
{
try {
// Validate the value...
} catch (Throwable $e) {
report($e);
return false;
}
}
HTTP Exceptions
# Controllers
Basic
namespace App\Http\Controllers;
use App\Http\Controllers\Controller;
use App\Models\User;
class UserController extends Controller
{
public function show($id)
{
return view('user.profile', [
'user' => User::findOrFail($id)
]);
}
use App\Http\Controllers\UserController;
# 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.
// ...
});
POST, PUT, PATCH, or DELETE forms should include a hidden CSRF _token field in the form to validate the request.
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
$uri = $request->path();
// * is wildcard
if ($request->is('admin/*')) {
//
}
if ($request->routeIs('admin.*')) {
//
}
URL
Request Method
$method = $request->method();
Client IP
$ipAddress = $request->ip();
Headers
$value = $request->header('X-Header-Name');
$contentTypes = $request->getAcceptableContentTypes();
if ($request->accepts(['text/html', 'application/json'])) {
// ...
}
Input
$input = $request->all();
$input = $request->collect();
See Helpers
$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');
$input = $request->input();
$name = $request->query('name');
$query = $request->query();
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;
$input = $request->except(['credit_card']);
$input = $request->except('credit_card');
Check Existence
if ($request->has('name')) {
//
}
$username = $request->old('username');
See: Helpers
See: Forms
Uploaded Files
$file = $request->file('photo');
$file = $request->photo;
$path = $request->photo->path();
$extension = $request->photo->extension();
# Views
Intro
<html>
<body>
<h1>Hello, <?php echo $name; ?></h1>
</body>
</html>
Create a view by placing a file with the .blade.php extension in the resources/views directory.
Pass Data to Views
As an array
Using with()
return view('greeting')
->with('name', 'Victoria')
->with('occupation', 'Astronaut');
<html>
<body>
<h1>Hello, {{ $name }}</h1>
<!-- Or -->
<h1>Hello, <?php echo $name; ?></h1>
</body>
</ht l>
view helper
Route::get('/', function () {
return view('greeting', ['name' => 'James']);
});
Subdirectories
// resources/views/admin.profile.blade.php
return view('admin.profile');
# Blade Templates
Intro
Blade is the templating engine included in Laravel that also allows you to use plain PHP.
Views
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
@isset($records)
// $records is defined and is not null...
@endisset
@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:
@if ($loop->last)
This is the last iteration.
@endif
Blade's echo statements {{ }} are automatically sent through PHP's htmlspecialchars function to prevent XSS attacks.
Including Subviews
<div>
<!-- resources/views/shared/errors/blade.php -->
@include('shared.errors')
<form>
<!-- Form Contents -->
</form>
</div>
Raw 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
<head>
<!-- Head Contents -->
@stack('scripts')
</head>
@push('scripts')
This will be second...
@endpush
// Later...
@prepend('scripts')
This will be first...
# Forms
Intro
CSRF Field
...
</form>
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:
<form action="/post/my-post" method="POST">
@method('PUT')
Validation Errors
@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');
Logic
// in routes/web.php
Route::get('/post/create', [App\Http\Controllers\PostController::class, 'create']);
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
after:date
Instead of a date string, you may specify another field to compare against the date
See before:date
after_or_equal:date
before:date
alpha_num
confirmed
current_password
date
Field must be a valid, non-relative date according to the strtotime PHP function.
file
max:value
min:value
mimetypes:text/plain,...
File must match one of the given MIME types:
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.
File's contents will be read and the framework will attempt to guess the MIME type, regardless of the client's provided MIME type.
nullable
numeric
password
prohibited
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
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
For numeric data: integer value (must also have the numeric or integer rule).
unique:table,column
url
Validate Passwords
$validatedData = $request->validate([
'password' => ['required', 'confirmed', Password::min(8)],
]);
Password rule object allows you to easily customize the password complexity requirements
Password::min(8)->uncompromised()
Uses the k-Anonymity model via the haveibeenpwned.com service without sacrificing the user's privacy or security
Password::min(8)
->letters()
->mixedCase()
->numbers()
->symbols()
->uncompromised()
<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
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
Validated Input
$validated = $request->validated();
Access as an array
$validated = $request->safe();
$email = $validated['email'];
# Session
Intro
Laravel ships with a variety of session backends that are accessed through a unified API. Memcached, Redis, and database support is included.
Configuration
if ($request->session()->exists('users')) {
//
}
if ($request->session()->missing('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');
Route::get('/home', function () {
// Retrieve a piece of data from the session...
$value = session('key');
$data = $request->session()->all();
$request->session()->put('key', 'value');
# Logging
Configuration
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;
Ensure your web server directs all requests to your application's public/index.php file
Optimization
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
Route Loading
View Loading
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.