Laravel Tutorial
Learn Laravel
The PHP framework for web artisans.
Stage 1
01
Getting Started
03
Controllers and Blade
Stage 2
04
Collections
05
String Helpers
06
Array Helpers
08
Dates with Carbon
Stage 3
09
Eloquent, Validation and Middleware
10
Migrations, Factories and Seeders
11
Advanced Eloquent
Stage 4
12
Requests and Validation
13
Authentication and Authorization
Stage 5
15
Building an API
16
Queues and Scheduled Work
17
Mail and Notifications
18
Events and Observers
Stage 6
19
Testing
20
Caching
21
Framework Internals
Stage 7
22
Performance
23
Deploying Laravel
Laravel Reference
258 pages · 11 groups · syntax, parameters and worked examples
Collection Methods63
Collection::allReturns the collection's underlying PHP array, with its keys intact.Collection::averageReturns the mean of the collection's values, optionally averaging one key or a computed value.Collection::chunkSplits the collection into a collection of smaller collections of the given size.Collection::collapseMerges a collection of arrays or collections into one flat collection, one level deep.Collection::combineUses the collection's values as keys and the given values as values, producing an associative collection.Collection::containsDetermines whether the collection holds a matching item, by value, key/value pair or truth test.Collection::countReturns the number of items in the collection.Collection::countByTallies how many times each value occurs, optionally grouping by a key or computed value.Collection::diffReturns the items whose values are not present in the given array or collection.Collection::eachRuns a callback over every item, stopping early when the callback returns false.Collection::everyDetermines whether every item passes the given truth test, returning true for an empty collection.Collection::exceptReturns all items apart from those stored under the given keys.Collection::filterKeeps only the collection items that pass a truth test, preserving their original keys.Collection::firstReturns the first item in a collection, optionally the first one passing a truth test.Collection::firstWhereReturns the first collection item matching a key/value or key/operator/value comparison.Collection::flatMapMaps each item through a callback and collapses the results by exactly one level.Collection::flattenFlattens a multi-dimensional collection into a single dimension, to an optional depth.Collection::getReturns the collection item stored at a given key, or a default when that key is absent.Collection::groupByGroups a collection's items into sub-collections keyed by a field or callback result.Collection::hasDetermines whether one key, or every key in a list, exists in the collection.Collection::implodeJoins collection items into a string, optionally plucking a key from each item first.Collection::intersectRemoves any values not present in the given array or collection, keeping the original keys.Collection::isEmptyReturns true when the collection contains no items at all.Collection::joinJoins collection values into a string, with a separate glue before the final element.Collection::keyByRe-keys a collection by a field or callback so items can be looked up by that value.Collection::keysReturns a new collection containing all of the original collection's keys as values.Collection::lastReturns the last item in the collection, or the last item passing a given truth test.Collection::mapRuns a callback over every item and returns a new collection of the returned values.Collection::mapWithKeysRebuilds a collection from key/value pairs returned by a callback for each item.Collection::maxReturns the largest value in the collection, optionally read from a key or callback.Collection::mergeMerges an array or collection into the collection, overwriting string keys and appending numeric ones.Collection::minReturns the smallest value in the collection, optionally read from a key or callback.Collection::onlyReturns a new collection containing just the items whose keys are in the given list.Collection::partitionSplits a collection into two collections: items passing a truth test and items failing it.Collection::pipePasses the whole collection to a closure and returns whatever that closure returns.Collection::pluckExtracts the values of one key from every item, optionally keying the result by another.Collection::randomPulls one item, or a given number of items, out of a collection at random.Collection::reduceFolds a collection down to one value by threading a carry through every item.Collection::rejectRemoves every item for which the given callback returns true, keeping the rest.Collection::reverseFlips the order of a collection's items while keeping each item's original key.Collection::shuffleReturns a new collection with the same items in a randomized order.Collection::skipDrops the given number of items from the front of a collection and returns the rest.Collection::sliceExtracts a portion of a collection starting at a given index, optionally limited in length.Collection::soleReturns the one item matching a test, throwing if zero or more than one match.Collection::sortOrders a collection by its values, keeping every item's original key.Collection::sortByOrders a collection by a field, a computed value, or several fields at once.Collection::sortByDescOrders a collection by a field or computed value from highest to lowest.Collection::sortKeysOrders an associative collection by its keys rather than by its values.Collection::sumAdds up every item in a collection, optionally reading one key or a closure from each row.Collection::takeReturns a new collection of the first n items, or the last n when the count is negative.Collection::takeWhileReturns items from the start until the callback first returns false, then stops iterating.Collection::toArrayConverts the collection to a plain array, turning any Arrayable items into arrays too.Collection::toJsonSerializes the collection to a JSON string, with optional json_encode flags.Collection::transformReplaces every item in place with the callback's return value, mutating the collection.Collection::uniqueRemoves duplicate items, optionally comparing one key or a computed value per row.Collection::valuesReturns a new collection with the keys reset to consecutive integers from zero.Collection::whenRuns a callback on the collection only when the given value is truthy, keeping the chain.Collection::whereFilters rows by a key/value pair, with an optional comparison operator.Collection::whereInKeeps only the rows whose value for a key appears in the given array.Collection::whereNotInRemoves the rows whose value for a key appears in the given array.Collection::whereNullFilters a collection down to the items whose value at the given key is strictly null.Collection::wrapWraps a scalar, array or existing collection in a collection without ever nesting one inside another.Collection::zipMerges the collection with one or more iterables by position, pairing item 0 with item 0.
Str Methods38
Str::replaceLastReplaces only the final occurrence of a substring, leaving every earlier match untouched.Str::singularConverts an English word to its singular form using Laravel's inflector.Str::slugTransliterates, lowercases and hyphenates a string into a URL-safe slug.Str::snakeConverts a camelCase or spaced string to snake_case with a configurable delimiter.Str::squishCollapses every run of whitespace to one space and trims both ends of the string.Str::startsWithDetermines whether a string begins with a given value or any value in a list.Str::studlyConverts a delimited or spaced string to StudlyCase for use as a class name.Str::substrReturns a portion of a string by character offset, safely handling multibyte text.Str::titleCapitalises the first letter of every word and lowercases the rest.Str::upperConverts a string to uppercase with full multibyte support.Str::wordCountCounts the words in a string, optionally treating extra characters as part of a word.Str::wordsTruncates a string to a maximum number of words and appends an ending.Str::uuidGenerates a random version 4 UUID as a Ramsey UuidInterface object.Str::markdownConverts GitHub flavored Markdown into an HTML string using League CommonMark.Str::afterReturns everything after the first occurrence of a value, or the whole string if it is absent.Str::afterLastReturns everything after the last occurrence of a value, or the whole string if it is absent.Str::asciiTransliterates a UTF-8 string into its closest plain ASCII equivalent.Str::beforeReturns everything before the first occurrence of a value, or the whole string if it is absent.Str::camelConverts a snake_case, kebab-case or spaced string to camelCase.Str::containsDetermines whether a string contains a given value, or any value from an array.Str::endsWithDetermines whether a string ends with a given value, or with any value from an array.Str::excerptExtracts a window of text around the first match of a phrase, with configurable radius and omission marker.Str::finishAppends a value to a string only if it does not already end with it.Str::headlineConverts camelCase, snake_case or kebab-case strings into space-separated Title Cased words.Str::initialsReturns the first letter of each whitespace-separated word, optionally upper-cased.Str::isDetermines whether a string matches a wildcard pattern, or any pattern from an array.Str::kebabConverts a camelCase or space-separated string to kebab-case using hyphens as word boundaries.Str::lengthReturns the number of characters in a string, counting multibyte characters as one each.Str::limitTruncates a string to a maximum display width and appends an ellipsis, optionally without splitting a word.Str::lowerConverts a string to lowercase, handling accented and non-Latin characters that strtolower ignores.Str::maskReplaces a portion of a string with a repeated character to redact card numbers, emails or phone numbers.Str::ofWraps a string in a Stringable object so string helpers can be chained fluently instead of nested.Str::passwordGenerates a random password of a given length containing letters, numbers and symbols.Str::pluralConverts an English word to its plural form, returning the singular when the count is exactly one.Str::randomGenerates a cryptographically secure random alphanumeric string of the requested length.Str::removeDeletes every occurrence of a value, or of each value in a list, from a string.Str::replaceReplaces every occurrence of a value in a string, with optional case-insensitive matching.Str::replaceFirstReplaces only the first occurrence of a value in a string and leaves later occurrences intact.
Arr Methods24
Arr::addSets an array key only when it is missing or null, leaving any existing value untouched.Arr::collapseMerges an array of arrays or collections one level down into a single flat array.Arr::dotFlattens a nested array into a single level whose keys use dot notation to show depth.Arr::undotExpands an array of dot-notation keys back into a nested multi-dimensional array.Arr::exceptReturns a copy of an array with the given keys removed, including nested dot-notation keys.Arr::firstReturns the first array element passing a truth test, or a default when nothing matches.Arr::flattenFlattens a nested array into a single-level list, discarding every key at every depth.Arr::forgetRemoves one or more keys from an array in place using dot notation for nested keys.Arr::getReads a value from a nested array by dot-notation path, returning a default when it is missing.Arr::hasChecks whether one or more dot-notation keys exist in an array, counting null values as present.Arr::isListReports whether an array's keys are sequential integers starting at zero with no gaps.Arr::keyByRe-keys an array of records by one of their fields or by the return value of a callback.Arr::lastReturns the last array element, or the last one that passes a given truth test.Arr::mapWithKeysRebuilds an array by letting a callback return the key and the value for each item.Arr::onlyReturns just the given keys from an array, dropping everything else.Arr::pluckExtracts one field from every row of an array, optionally keying the result by another field.Arr::pullReads a value from an array and removes that key in one step.Arr::randomReturns one random value from an array, or an array of several when a count is given.Arr::setWrites a value into a nested array using dot notation, creating any missing levels.Arr::sortSorts an array by its values, by a dot-notation key, or by the result of a callback.Arr::toCssClassesCompiles an array of conditional classes into a single CSS class string.Arr::whereFilters an array with a callback that receives both the value and the key.Arr::whereNotNullRemoves every null value from an array while leaving other falsy values in place.Arr::wrapWraps a value in an array, passing arrays through unchanged and turning null into an empty array.
Number Methods14
Number::formatFormats an int or float into a locale-aware decimal string with thousands separators.Number::currencyFormats a value as currency, choosing the symbol and its placement from the locale.Number::percentageFormats a value as a locale-aware percentage string, treating 12.5 as 12.5%.Number::abbreviateShortens a large number to compact notation, turning 1337 into 1K and 1230000 into 1.23M.Number::forHumansConverts a large number to a readable scale phrase such as 1.23 million.Number::fileSizeConverts a byte count into a readable size string such as 1 KB or 2.5 MB.Number::ordinalConverts a number to its ordinal form, turning 1 into 1st and 11 into 11th.Number::spellSpells a number out in words, with optional thresholds for where spelling starts or stops.Number::spellOrdinalSpells a number's ordinal form as words, turning 3 into third and 21 into twenty-first.Number::clampConstrains a number to a minimum and maximum, returning the nearest bound when it falls outside.Number::trimRemoves trailing zero digits after the decimal point, turning 12.30 into 12.3.Number::pairsSplits a range into consecutive [start, end] buckets for pagination or histogram bands.Number::parseParses a locale-formatted numeric string into an int or float using the intl NumberFormatter.Number::withLocaleRuns a callback with Number's locale temporarily set, restoring the previous locale afterwards.
Helper Functions27
collectCreate a Collection from an array, iterable, Arrayable or null.data_getRead a nested value from an array or object using dot notation, with a default.data_setWrite a value into a nested array or object by dot path, creating missing levels.data_fillWrite a nested value only where one is missing, leaving existing values untouched.data_forgetRemove a nested key from an array or object using dot notation.tapPass a value to a closure for side effects and return the original value.valueInvoke the argument if it is a closure, otherwise return it unchanged.blankDetermine whether a value is blank, treating whitespace-only strings as empty.filledDetermine whether a value is not blank, counting 0 and false as real values.optionalAccess properties and methods on a possibly-null value without raising an error.strCreate a fluent Stringable from a string, or a proxy to the static Str methods.headReturn the first element of an array, or false when the array is empty.lastReturns the last element of an array, or false when the array is empty.withReturns the given value, optionally passing it through a closure first.transformApplies a callback only when the value is filled, returning a default for blank values.throw_ifThrows the given exception when the condition is truthy, collapsing a guard clause to one line.throw_unlessThrows the given exception when the condition is falsy, the positive form of a throw_if guard.class_basenameReturns a class name with its namespace stripped, from either a string or an object.eEscapes HTML special characters the same way Blade's double braces do.retryRe-runs a callback until it succeeds or the attempt budget runs out, sleeping in between.preg_replace_arrayReplaces each match of a pattern with the next value from an array, in order.literalBuilds an stdClass from named arguments for a quick, throwaway value object.configReads and sets configuration values by dot notation through the container's repository.appReturns the service container, or resolves the given class or binding out of it.envReads an environment variable loaded from .env, returning a default when the key is not set.requestReturns the current HTTP request instance, or pulls a single input value out of it.ddDumps the given variables with the var dumper and immediately ends the script.
Carbon and Date Helpers16
nowReturns a Carbon instance for the current date and time in the application timezone.todayReturns a Carbon instance for the current date with the time set to 00:00:00.Carbon::parseBuilds a Carbon instance from almost any date string, including relative phrases like 'next friday'.Carbon::createBuilds a Carbon instance from explicit year, month, day and time parts.Carbon::createFromFormatParses a date string against an exact format, rejecting input that does not match.Carbon::addDaysAdds a number of days to a Carbon instance, mutating it in place.Carbon::subDaysSubtracts a number of days from a Carbon instance, mutating it in place.Carbon::diffForHumansRenders the gap between two dates as a readable phrase such as '3 hours ago'.Carbon::diffInDaysReturns the number of days between two dates as a signed float.Carbon::formatFormats a date using PHP's date() format characters.Carbon::startOfDayResets the time on a Carbon instance to 00:00:00 on the same date.Carbon::endOfMonthMoves a Carbon instance to the last day of its month at 23:59:59.999999.Carbon::isWeekendReturns true when the date falls on one of the configured weekend days, Saturday or Sunday by default.Carbon::isPastReturns true when the instance is strictly earlier than the current moment.Carbon::setTimezoneConverts the instance to another timezone, changing the displayed clock time but not the underlying instant.Carbon::toDateStringFormats the instance as a Y-m-d date string in its own timezone, dropping the time portion.
Eloquent Query Methods21
Model::limitCaps how many rows an Eloquent query returns by setting the SQL LIMIT clause.Model::countRuns a SQL COUNT for the query and returns the number of matching rows as an integer.Model::createMass assigns an array of attributes to a new model, saves it, and returns the saved instance.Model::firstOrCreateFinds the first row matching the given attributes, or inserts one merged with the extra values.Model::updateOrCreateUpdates the first row matching the given attributes, or inserts one when nothing matches.Model::savePersists a model, inserting a new row or updating the existing one depending on its state.Model::deleteRemoves the model's row from the database, or sets deleted_at when the model uses SoftDeletes.Model::paginateReturns one page of results plus the totals needed to render numbered pagination links.Model::chunkProcesses query results in fixed-size batches so large tables never load fully into memory.Model::allRetrieves every row from the model's table as an Eloquent Collection of hydrated models.Model::findLooks up a model by its primary key, returning the model or null when no row matches.Model::findOrFailLooks up a model by primary key and throws ModelNotFoundException when no row matches.Model::whereAdds a where clause to the query, inferring the = operator when you pass only a value.Model::orWhereJoins a condition to the query with OR instead of AND, accepting the same arguments as where().Model::whereInConstrains a query to rows whose column value appears in a given array or subquery.Model::whereNullConstrains a query to rows where the given column or columns are SQL NULL.Model::whereHasFilters models by a constrained relationship, compiling the check into an EXISTS subquery.Model::withEager loads the named relationships, replacing the N+1 query pattern with a fixed query count.Model::withCountAdds a {relation}_count attribute via a subselect without loading any of the related rows.Model::orderBySorts query results by a column in ascending or descending order, defaulting to ascending.Model::latestOrders results newest first by the model's created_at column, or by a column you name.
Routing11
Route::getRegisters a route that answers GET and HEAD requests at the given URI.Route::postRegisters a route that answers POST requests, typically for creating a resource.Route::putRegisters a route that answers PUT requests, replacing a resource in full.Route::deleteRegisters a route that answers DELETE requests for removing a resource.Route::resourceRegisters the seven conventional CRUD routes for a controller in one declaration.Route::apiResourceRegisters the five API CRUD routes, omitting the HTML create and edit forms.Route::groupApplies shared attributes such as middleware, prefixes and names to a set of routes.Route::middlewareAttaches middleware to a route or to every route in a group, in the order listed.Route::nameNames a route, or prefixes the names of every route inside a group.Route::prefixPrepends a URI segment to every route defined inside the group.Route::whereConstrains a route parameter with a regular expression so non-matching URIs 404.
Validation Rules19
requiredRequires the field to be present and not null, an empty string, an empty array or a pathless upload.required_ifRequires the field to be present and not empty when another field equals one of the given values.nullableAllows null to pass while the field's other rules still apply to any non-null value.sometimesRuns the field's remaining rules only when the key is actually present in the input data.emailValidates an email address, optionally layering rfc, strict, dns, spoof or filter checks.minEnforces a minimum size: characters, numeric value, array count or file kilobytes.maxCaps a field's size: characters, numeric value, array count or file kilobytes.betweenRequires a size between two inclusive bounds, measured by the field's own type.confirmedRequires a matching {field}_confirmation input, or a custom field named after the colon.uniqueFails when the value already exists in the given database table column.existsFails unless the value already exists in the given database table column.inRestricts the value to a fixed list of allowed options.numericValidates that a field is numeric, accepting integers, floats and numeric strings from request input.integerValidates that a field is an integer as accepted by PHP's FILTER_VALIDATE_INT filter.booleanValidates that a field can be cast to a boolean, accepting only true, false, 1, 0, "1" and "0".arrayValidates that a field is a PHP array and, when keys are listed, that it contains no unexpected keys.dateValidates that a field is a valid, non-relative date according to PHP's strtotime function.regexValidates a field against a regular expression using PHP's preg_match, delimiters included.urlValidates that a field is a well-formed URL, optionally restricted to a list of allowed protocols.
Blade Directives13
{{ }}Prints a PHP expression into a template, escaped through htmlspecialchars to prevent XSS.@ifRenders a block of a template only when a PHP expression evaluates to true.@unlessRenders a block only when an expression is falsy, reading as the inverse of a conditional.@foreachIterates an array or collection in a template and exposes loop metadata through $loop.@forelseLoops over an iterable and renders an alternative block when it yields no items.@switchSelects one of several template branches by matching a value against @case labels.@includeRenders another view inside the current one, passing along all of the parent's data.@extendsDeclares the layout a child view inherits, filling its sections with the child's content.@sectionDefines a named block of content that a layout renders where it yields that name.@yieldRenders a named section from a layout, with an optional fallback when nothing filled it.@csrfOutputs the hidden token field every POST, PUT, PATCH or DELETE form needs to pass CSRF checks.@methodEmits the hidden _method field that spoofs PUT, PATCH and DELETE from an HTML form.@errorRenders a block when a field has a validation error and exposes its first message as $message.
Cache and Storage12
Cache::getReads a value from the cache, returning null or a supplied default when the key is not present.Cache::putWrites a value to the cache for a given number of seconds, or forever when the TTL is omitted.Cache::rememberReturns a cached value, or runs the closure once and caches its result for the given lifetime.Cache::foreverStores an item in the cache with no expiration, removable only by forget, flush or eviction.Cache::forgetRemoves a single item from the cache and reports whether the key was actually there.Cache::incrementAdds an amount to an integer cache item, atomically on Redis and Memcached.Storage::diskReturns the filesystem instance for a named disk from config/filesystems.php.Storage::putWrites contents to a path on a disk, accepting a string, a stream or an uploaded file.Storage::getReads a file from a disk and returns its raw contents as a string, or null when it is missing.Storage::existsReports whether a path exists on a disk, returning true for directories as well as files.Storage::deleteDeletes one path or an array of paths from a disk, treating an already-absent file as success.Storage::urlBuilds the public URL for a file on a disk whose driver can expose one.
All Laravel reference pages A–Z
A
C
Collection::allCollection::averageCollection::chunkCollection::collapseCollection::combineCollection::containsCollection::countCollection::countByCollection::diffCollection::eachCollection::everyCollection::exceptCollection::filterCollection::firstCollection::firstWhereCollection::flatMapCollection::flattenCollection::getCollection::groupByCollection::hasCollection::implodeCollection::intersectCollection::isEmptyCollection::joinCollection::keyByCollection::keysCollection::lastCollection::mapCollection::mapWithKeysCollection::maxCollection::mergeCollection::minCollection::onlyCollection::partitionCollection::pipeCollection::pluckCollection::randomCollection::reduceCollection::rejectCollection::reverseCollection::shuffleCollection::skipCollection::sliceCollection::soleCollection::sortCollection::sortByCollection::sortByDescCollection::sortKeysCollection::sumCollection::takeCollection::takeWhileCollection::toArrayCollection::toJsonCollection::transformCollection::uniqueCollection::valuesCollection::whenCollection::whereCollection::whereInCollection::whereNotInCollection::whereNullCollection::wrapCollection::zipcollectclass_basenameconfigCarbon::parseCarbon::createCarbon::createFromFormatCarbon::addDaysCarbon::subDaysCarbon::diffForHumansCarbon::diffInDaysCarbon::formatCarbon::startOfDayCarbon::endOfMonthCarbon::isWeekendCarbon::isPastCarbon::setTimezoneCarbon::toDateStringconfirmed@csrfCache::getCache::putCache::rememberCache::foreverCache::forgetCache::increment
H
M
Model::limitModel::countModel::createModel::firstOrCreateModel::updateOrCreateModel::saveModel::deleteModel::paginateModel::chunkModel::allModel::findModel::findOrFailModel::whereModel::orWhereModel::whereInModel::whereNullModel::whereHasModel::withModel::withCountModel::orderByModel::latestminmax@method
N
R
S
Str::replaceLastStr::singularStr::slugStr::snakeStr::squishStr::startsWithStr::studlyStr::substrStr::titleStr::upperStr::wordCountStr::wordsStr::uuidStr::markdownStr::afterStr::afterLastStr::asciiStr::beforeStr::camelStr::containsStr::endsWithStr::excerptStr::finishStr::headlineStr::initialsStr::isStr::kebabStr::lengthStr::limitStr::lowerStr::maskStr::ofStr::passwordStr::pluralStr::randomStr::removeStr::replaceStr::replaceFirststrsometimes@switch@sectionStorage::diskStorage::putStorage::getStorage::existsStorage::deleteStorage::url