Configuration
.env
Retrieve values from .env file
|
|
Determine current environment
|
|
Accessing configuration values using “dot” syntax
|
|
Set configuration values at runtime:
|
|
Debug Mode
Turn on (local dev):
|
|
Turn off (production):
|
|
Maintenance Mode
Temporarily disable application (503 status code)
|
|
Disable maintenance mode
|
|
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
|
|
Multiple HTTP methods
|
|
Basic Definition
|
|
Dependency Injection
|
|
Type hint concrete dependencies for auto-injection
View Routes
|
|
Route only needs to return a view.
Route Model Binding
Implicit binding
With closure
|
|
With controller action
|
|
With custom resolution column
|
|
Always use a different column to resolve
|
|
Multiple models - second is child of first
|
|
Convenient way to automatically inject the model instances directly into your routes
Route Parameters
Capture segments of the URI within your route
Required parameters
|
|
With dependency injection
|
|
Optional Parameters
|
|
Redirect Routes
HTTP 302 status
|
|
Set the status code
|
|
Permanent 301 redirect
|
|
Regular Expression Constraints
|
|
See also: Regex Cheatsheet
Named Routes
Route names should always be unique
|
|
See: Helpers
Fallback Routes
|
|
Executed when no other routes match
Route Groups
Middleware
|
|
URI Prefixes
|
|
Name Prefix
|
|
Share attributes across routes
Accessing current route
|
|
Helpers
routes
Named route
|
|
With parameters
|
|
With query string
|
|
Redirects
|
|
Eloquent Models
|
|
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
|
|
Current URL
|
|
Named Route URL
|
|
See Named Route
Error Handling
|
|
Report an exception but continue handling the current request
HTTP Exceptions
|
|
Generate an HTTP exception response using status code
Controllers
Basic
|
|
Define a route for this controller method:
|
|
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:
|
|
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
|
|
Path
The request’s path information
|
|
Match path to pattern
Verify that the incoming request path matches a given pattern
|
|
Determine if the incoming request matches a named route
|
|
URL
Full URL for the incoming request
|
|
Request Method
|
|
Client IP
|
|
Headers
|
|
Content Type
Return an array containing all the content types accepted by the request
|
|
Boolean check for content types are accepted by the request
|
|
Input
Retrieve all the incoming request’s input data as an array
|
|
Retrieve all the incoming request’s input data as a collection
|
|
See Helpers
Retrieve user input (also gets values from query string)
|
|
Access array inputs
|
|
Retrieve all the input values as an associative array:
|
|
Only retrieve values from the query string:
|
|
Retrieve all the query string values as an associative array:
|
|
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
|
|
Dynamic Properties
Access inputs via properties. If not found as an input, the route parameters will be checked.
|
|
Retrieve Partial Input
|
|
Check Existence
Determine if value(s) present
|
|
Old Input
Retrieve input from the previous request
|
|
Or use the old() helper
|
|
Uploaded Files
Retrieve uploaded file from request
|
|
Get file path or extension
|
|
Store uploaded file with a randomly generated filename
|
|
Store uploaded file and specify the name
|
|
See More: Laravel File Storage
Views
Intro
|
|
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()
|
|
Access each value using the data’s keys
|
|
view helper
Return a view from a route with the view() helper
|
|
See: View Routes and Helpers
Subdirectories
|
|
Blade Templates
Intro
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
|
|
See: Views
Comments
|
|
Directives
if Statements
|
|
isset & empty
|
|
Authentication
|
|
Loops
|
|
Loop Iteration:
|
|
See more: Laravel Loop Variable
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:
|
|
Display results of a PHP function:
|
|
Display data without escaping with htmlspecialchars
|
|
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
|
|
Raw PHP
Execute a block of plain PHP
|
|
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
|
|
Render the stack
|
|
Prepend to the beginning of a stack
|
|
Forms
Intro
CSRF Field
Include a hidden CSRF token field to validate the request
|
|
See: CSRF Protection
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:
|
|
Validation Errors
|
|
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
|
|
Or the old() helper
|
|
Validation
Intro
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
|
|
Rules
Can also be passed as an array
|
|
after:date
Field must be a value after a given date.
|
|
Instead of a date string, you may specify another field to compare against the 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.
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:
|
|
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.
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
Countableobject. - 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
numericorintegerrule). - For arrays: count of the array
- For files: file size in kilobytes
|
|
unique:table,column
Field must not exist within the given database table
url
Field must be a valid URL
Validate Passwords
Ensure passwords have an adequate level of complexity
|
|
Password rule object allows you to easily customize the password complexity requirements
|
|
Ensure a password has not been compromised in a public password data breach leak
|
|
Uses the k-Anonymity model via the haveibeenpwned.com service without sacrificing the user’s privacy or security
Methods can be chained
|
|
Display Validation Errors
|
|
See: Validation 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
|
|
Validated Input
Retrieve the request data that underwent validation
|
|
Or with safe(), which returns an instance of Illuminate\Support\ValidatedInput
|
|
Iterate
|
|
Access as an array
|
|
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
Session configuration is in config/session.php.
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:
|
|
Returns true if present, even if it’s null:
|
|
Returns true if the item is null or is not present:
|
|
Retrieving Data
Via Request
|
|
Pass a default value as the second argument to use if the key does not exist
|
|
Via session helper
|
|
See: Session Helper
All Session Data
|
|
Retrieve and Delete
Retrieve and delete an item from the session
|
|
Store Data
Via a request instance
|
|
Via the global “session” helper
|
|
Push a new value onto a session value that is an array
|
|
Logging
Configuration
Configuration options for logging behavior is in config/logging.php.
By default, Laravel will use the stack channel when logging messages, which aggregates multiple log channels into a
single channel.
Levels
All the log levels defined in the RFC 5424 specification are available:
- emergency
- alert
- critical
- error
- warning
- notice
- info
- debug
Log Facade
|
|
Contextual Info
|
|
Deployment
Intro
Ensure your web server directs all requests to your application’s public/index.php file
Optimization
Composer’s autoloader map
|
|
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.