This repository contains notes and topics related to Laravel PHP Framework. This is gives some useful comments and code samples. For complete usage, refer offical documentation.
composer global require laravel/installer
laravel new example-app
laravel new example-app --git
laravel new example-app --git --branch="main"
cd example-app
php artisan serve
php artisan down --refresh=15
refresh the page every 15 seconds
php artisan down --retry=60
php artisan down --secret="1234542a-246b-4b66-afa1-dd72a4c43515"
via following URL with secret key : https://example.com/1234542a-246b-4b66-afa1-dd72a4c43515
php artisan down --render="errors::503"
php artisan down --redirect=/
php artisan up
php artisan storage:link
this will generate symbolic link for the publicly available directory that storage/app/public into public/storage.
php artisan list make
That commands originated from console directory inside app directory.
This will have all essential technique, performance optimization and security features implementation with it.
Here are some as follows: 1. Server Requirement to run application, 2. Server configuration (example: pointing to public/index.php), 3. Autoloader optimization, 4. configuration cache (env file will never used after that), 5. route cache, 6. view cache,
all before process set debug mode false.
Follow the bellow link or check for any other versions.
https://laravel.com/docs/9.x/deployment
The first parameter is referred to the request and second to the callback in different method as given further below 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);
Returning text for the request.
use Illuminate\Support\Facades\Route;
Route::get('/greeting', function () {
return 'Hello World';
});
Returning to controller method for the request.
use App\Http\Controllers\UserController;
Route::get('/user', [UserController::class, 'index']);
This will check request method as mention in the first parameter array.
Route::match(['get', 'post'], '/', function () {
//
});
This will take request with any of the request method.
Route::any('/', function () {
//
});
Simple redirection for the request URL.
Route::redirect('/here', '/there');
Redirection with status code for the requested URL.
Route::redirect('/here', '/there', 301);
Permanent Redirection with status code 301 for the requested URL.
Route::permanentRedirect('/here', '/there');
Returning the view page / file for the requested URL.
Route::view('/welcome', 'welcome');
This will additionally pass some data to it.
Route::view('/welcome', 'welcome', ['name' => 'Taylor']);
Routes with required URL parameter.
Route::get('/user/{id}', function ($id) {
return 'User '.$id;
});
Routes with many parameter required and that parameter should be positional.
Route::get('/posts/{post}/comments/{comment}', function ($postId, $commentId) {
//
});
Route parameter with dependency injection. Here, Request is dependency. That is injected with URL parameter.
use Illuminate\Http\Request;
Route::get('/user/{id}', function (Request $request, $id) {
return 'User '.$id;
});
Route with optional URL parameters.
Route::get('/user/{name?}', function ($name = 'Guest') {
return 'User name : ' . $name;
});
Route URL parameters with regular expression constrains. That accepts request only if valid.
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]+']);
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');
Route::get('/category/{category}', function ($category) {
//
})->whereIn('category', ['movie', 'song', 'painting']);
It need to define inside boot method in the App\Providers\RouteServiceProvider Class. and this will recognize id URL parameter wherever is defined also need not to call where constrain for that parameters in routes\web.php file.
Route::pattern('id', '[0-9]+');
This will take {search} parameter for the link example.com/search/food/rise as food/rise.
Route::get('/search/{search}', function ($search) {
return $search;
})->where('search', '.*');
Route::get('/user/profile', function () {
//
})->name('profile');
This URL will be named as profile and Wherever Profile name used that URL again generated.
$url = route('profile');
$url = route('profile', ['id' => 1]); # for URL parameter.
return redirect()->route('profile');
Inspecting / Checking current route:
if ($request->route()->named('profile')) {
//
}
This will apply middleware for all other routes inside this group.
Route::middleware(['first', 'second'])->group(function () {
Route::get('/', function () {
// Uses first & second middleware...
});
Route::get('/user/profile', function () {
// Uses first & second middleware...
});
});
This will target specific controller for all other routes inside this group.
Route::controller(OrderController::class)->group(function () {
Route::get('/orders/{id}', 'show');
Route::post('/orders', 'store');
});
The route group can target and apply all other additional information to all routes with it for sub-domain purpose.
Route::domain('{account}.example.com')->group(function () {
Route::get('user/{id}', function ($account, $id) {
//
});
});
The route group can be used for creating prefix route for all other routes inside it. Here prefixes URL with admin.
Route::prefix('admin')->group(function () {
Route::get('/users', function () {
// Matches The "/admin/users" URL
});
});
The route group can be used for creating prefix named route for all other routes inside it. Here Prefixes name for named routes with admin.
Route::name('admin.')->group(function () {
Route::get('/users', function () {
// Route assigned name "admin.users"...
})->name('users');
});
$url = route('admin.users');
This will handle 404 not found by this method.
Route::fallback(function () {
//
});
This will limit traffic to specific route / URL. and this can be defined inside App\Providers\RouteServiceProvider class.
use Illuminate\Cache\RateLimiting\Limit;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\RateLimiter;
protected function configureRateLimiting()
{
RateLimiter::for('global', function (Request $request) {
return Limit::perMinute(1000);
});
}
RateLimiter::for('global', function (Request $request) {
return Limit::perMinute(1000)->response(function (Request $request, array $headers) {
return response('Custom response...', 429, $headers);
});
});
Get current route, name and action.
$route = Route::current();
$name = Route::currentRouteName();
$action = Route::currentRouteAction();
Get all routes available.
php artisan route:list
Get all routes available with middleware.
php artisan route:list -v
Get all routes created by developer.
php artisan route:list --except-vendor
Get all routes available by application itself.
php artisan route:list --only-vendor
Route Caching:
php artisan route:cache
Route Cache Clearing:
php artisan route:clear
Middlewares provide convenient way to filters requests and perform some actions based on conditions. example: Authentication middleware can check requested user is logined or not. if the user is not loggined then redirected to login page.
Middlewares can be created via following artisan command. EnsureTokenIsValid class created inside app/Http/Middleware.
php artisan make:middleware EnsureTokenIsValid
If middleware need to be used then need to registered inside app/Http/Kernel.php in the routeMiddleware.
Apply single middleware for specific request URL.
Route::get('/profile', function () {
//
})->middleware('auth');
Apply multiple middlewares for specific request URL.
Route::get('/', function () {
//
})->middleware(['first', 'second']);
Apply middleware without specifying the name but fully qualified class.
use App\Http\Middleware\EnsureTokenIsValid;
Route::get('/profile', function () {
//
})->middleware(EnsureTokenIsValid::class);
Route::middleware([EnsureTokenIsValid::class])->group(function () {
Route::get('/', function () {
//
});
Route::get('/profile', function () {
//
})->withoutMiddleware([EnsureTokenIsValid::class]);
});
Route::withoutMiddleware([EnsureTokenIsValid::class])->group(function () {
Route::get('/profile', function () {
//
});
});
Group of global middleware group can be registered inside App\Providers\RouteServiceProvider for corresponding web.php and or api.php route files. That route group can be applied as following ways.
Route::get('/', function () {
//
})->middleware('web');
Route::middleware(['web'])->group(function () {
//
});
The middlewares can be sorted / priority assigned when it is falls under group of middlewares. That can be implemented inside app/Http/Kernel.php file with property name called $middlewarePriority.
Middleware can accept parameters when implementing.
Route::put('/post/{id}', function ($id) {
//
})->middleware('role:editor');
After response if need to do something with middleware then terminate method will used.
CSRF token needed if any form has following method POST, PUT, PATCH and DELETE request methods.
Blade directive to generate hidden csrf field using @csrf representation. or equivalent with
<input type="hidden" name="_token" value="{{ csrf_token() }}" />
$token = $request->session()->token();
$token = csrf_token();
Adding their URLs to the $except property of the VerifyCsrfToken middleware implementation inside App\Providers\RouteServiceProvider class.
protected $except = [
'stripe/*',
'http://example.com/foo/bar',
'http://example.com/foo/*',
];
The App\Http\Middleware\VerifyCsrfToken middleware will also check for X-CSRF-TOKEN in requests. So, this can be implemented as follows.
<meta name="csrf-token" content="{{ csrf_token() }}">
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
Laravel stores the current CSRF token in the form of an encrypted XSRF-TOKEN as cookie.
Controllers are logical block of code that can be control the flow of application request. Controllers can have mulitple methods and some controller may have single method. This controllers are used in the Routes file.
php artisan make:controller ProvisionServer
php artisan make:controller ProvisionServer --invokable
This will create default methods for Create, Read, Edit, Update and Delete actions.
php artisan make:controller CrudController --resource
This will bind specific model class to the controller with CRUD resources.
php artisan make:controller PhotoController --model=Photo --resource
This will generate Form Request classes for that controller with CRUD resources.
php artisan make:controller PhotoController --model=Photo --resource --requests
Define and implement __invoke method inside controller class. This will not require to specify method name in Route files.
Route::post('/server', ProvisionServer::class);
Middlewares can be implemented inside constructor method or In the Route itself.
This will redirect to specific method by default for crud operation.
Route::resources([
'photos' => PhotoController::class,
'posts' => PostController::class,
]);
To avoid 404 page not found error and redirect to specific action can be done by adding missing method in Route resources.
Route::resource('photos', PhotoController::class)->missing(function (Request $request) {
return Redirect::route('photos.index');
});
This will redirect to specific method of action that are mentioned here
Route::resource('photos', PhotoController::class)->only([
'index', 'show'
]);
This will redirect to specific method except following method of action that are mentioned here
Route::resource('photos', PhotoController::class)->except([
'create', 'store', 'update', 'destroy'
]);
This will consumed by API requests.
Route::apiResource('photos', PhotoController::class);
Route::apiResources([
'photos' => PhotoController::class,
'posts' => PostController::class,
]);
The nested route resources for the requests /photos/{photo}/comments/{comment} will be declared as follows.
Route::resource('photos.comments', PhotoCommentController::class);
Assigning name for specific method of action.
Route::resource('photos', PhotoController::class)->names([
'create' => 'photos.build'
]);
To take up named parameter for requested URL /users/{admin_user} defined as follows.
Route::resource('users', AdminUserController::class)->parameters([
'users' => 'admin_user'
]);
$uri = $request->path();
To check the requested path is starting with admin/ or not.
if ($request->is('admin/*')) {
//
}
To check the route name is starting with admin or not.
if ($request->routeIs('admin.*')) {
//
}
Get requested URL without query string.
$url = $request->url();
Get requested URL with query string.
$urlWithQueryString = $request->fullUrl();
$request->fullUrlWithQuery(['type' => 'article']);
$request->host();
$request->httpHost();
$request->schemeAndHttpHost();
Get current requested method.
$method = $request->method();
Check current request method.
if ($request->isMethod('post')) {
//
}
Get Header value in the request.
$value = $request->header('X-Header-Name');
Get Header value if it not present retrieve default value.
$value = $request->header('X-Header-Name', 'default');
Check the request has specific header.
if ($request->hasHeader('X-Header-Name')) {
//
}
Get authorization header if present.
$token = $request->bearerToken();
$ipAddress = $request->ip();
Get acceptable content type for the request.
$contentTypes = $request->getAcceptableContentTypes();
Check acceptable content type for the request which returns either true
or false
.
if ($request->accepts(['text/html', 'application/json'])) {
// ...
}
Checks preferable content type for the request which returns null
if not present.
$preferred = $request->prefers(['text/html', 'application/json']);
Checks expected content type for the request which returns either true
or false
.
This will suitable for most requested type in web applications.
if ($request->expectsJson()) {
// ...
}
Laravel supports PSR-7 request type for more see Laravel-9-documentation
Get input data as array.
$input = $request->all();
Get input data as collection.
$input = $request->collect();
Get subset incoming request.
$request->collect('users')->each(function ($user) {
// ...
});
Get specific input values from the request.
$name = $request->input('name');
If input value not present get default value.
$name = $request->input('name', 'Sally');
Get first index of array input value.
$name = $request->input('products.0.name');
Get all array input value.
$names = $request->input('products.*.name');
Get all input values as associative array.
$input = $request->input();
Get specific query input value.
$name = $request->query('name');
Get specific query value when it not present return default value.
$name = $request->query('name', 'Helen');
Get all query string input value.
$query = $request->query();
Get specific input value when JSON request is made.
$name = $request->input('user.name');
Get specific input value when it is a stringable value.
$name = $request->string('name')->trim();
Get specific input value when it is a boolean value.
$archived = $request->boolean('archived');
Get specific input value when it is a date value.
$birthday = $request->date('birthday');
Get specific date input with timezone and additional formattings.
$elapsed = $request->date('elapsed', '!H:i', 'Asia/Kolkata');
Get specific input value via dynamic property which points form input field name.
$name = $request->name;
Get specific portion of input as array or dynamic list of arguments.
$input = $request->only(['username', 'password']);
$input = $request->only('username', 'password');
Get all portion of input as array or dynamic list of arguments except specific list of input.
$input = $request->except(['credit_card']);
$input = $request->except('credit_card');
Check whether input exists or not.
if ($request->has('name')) {
//
}
Check specific group of input present or not.
if ($request->has(['name', 'email'])) {
//
}
Check any one of specific input group present or not which returns true
or false
.
if ($request->hasAny(['name', 'email'])) {
//
}
Checks the specific input value not empty or not which returns true
or not
.
if ($request->filled('name')) {
//
}
Checks if the input key is missing in request which returns true
or false
.
if ($request->missing('name')) {
//
}
Execute closure when specific input value present.
$request->whenHas('name', function ($input) {
//
});
Execute closure when specific input value present and not present conditions.
$request->whenHas('name', function ($input) {
// The "name" value is present...
}, function () {
// The "name" value is not present...
});
Executes closure when input value is not empty.
$request->whenFilled('name', function ($input) {
//
});
Execute closure when input value is not empty and empty conditions.
$request->whenFilled('name', function ($input) {
// The "name" value is filled...
}, function () {
// The "name" value is not filled...
});
Merging additional input values to excisting request.
$request->merge(['votes' => 0]);
Merging additional input values if the key is missing.
$request->mergeIfMissing(['votes' => 0]);
It is useful when handling validation with existing forms to retrieving old form data.
For more see Laravel-9-documentation
The flash method useful to store all input to the flash session until next resquest.
$request->flashOnly(['username', 'email']);
$request->flashExcept('password');
Redirecting to previous page with old input by chaining the redirection with flash input.
return redirect('form')->withInput();
return redirect()->route('user.create')->withInput();
return redirect('form')->withInput(
$request->except('password')
);
Retrieving old input from flash.
$username = $request->old('username');
<input type="text" name="username" value="{{ old('username') }}">
Retrieving cookie value from request.
$value = $request->cookie('name');
Laravel supports Input Trimming and Normalization for more see Laravel-9-documentation
Get uploaded file from request.
$file = $request->file('photo');
$file = $request->photo;
Check file has uploaded by hasFile
.
if ($request->hasFile('photo')) {
//
}
Validate file upload has completed without any problem and it checks any uploaded error during request.
if ($request->file('photo')->isValid()) {
//
}
Get uploaded file path and extension.
$path = $request->photo->path();
$extension = $request->photo->extension();
Storing uploaded file.
$path = $request->photo->store('images');
$path = $request->photo->store('images', 's3');
Storing uploaded file in a specific disk name.
$path = $request->photo->storeAs('images', 'filename.jpg');
$path = $request->photo->storeAs('images', 'filename.jpg', 's3');
Laravel supports trust proxies for more see Laravel-9-documentation
Laravel supports trust host for more see Laravel-9-documentation