Laravel – Quick Guide
Laravel – Overview
Laravel is an open-source PHP web application framework designed to make modern web development easier, more expressive, and more maintainable.
Laravel follows the Model-View-Controller (MVC) architectural pattern and provides tools for:
-
Routing
-
Controllers
-
Views and Blade templates
-
Database access
-
Eloquent ORM
-
Authentication and authorization
-
Validation
-
Sessions and cookies
-
File storage and uploads
-
Mail and notifications
-
Queues and jobs
-
Events and listeners
-
Caching
-
Task scheduling
-
APIs
-
Testing
-
Artisan commands
Laravel applications are commonly managed with Composer, PHP’s dependency manager.
Laravel – Installation
A Laravel development environment generally requires:
-
PHP
-
Composer
-
A database such as MySQL, PostgreSQL, SQLite, or SQL Server
-
Node.js and npm when frontend asset compilation is required
Create a new Laravel application with:
composer create-project laravel/laravel example-app
Move into the project:
cd example-app
Start the development server:
php artisan serve
The application can then be accessed through the local development URL displayed by Artisan.
Laravel – Application Structure
A typical Laravel project contains directories such as:
example-app/
├── app/
├── bootstrap/
├── config/
├── database/
├── public/
├── resources/
├── routes/
├── storage/
├── tests/
├── vendor/
├── .env
├── artisan
├── composer.json
├── package.json
└── vite.config.js
Important directories include:
| Directory | Purpose |
|---|---|
app/ |
Application code |
bootstrap/ |
Framework bootstrapping |
config/ |
Configuration files |
database/ |
Migrations, factories, and seeders |
public/ |
Public entry point and assets |
resources/ |
Views, CSS, and JavaScript |
routes/ |
Application route definitions |
storage/ |
Logs, cache, sessions, and generated files |
tests/ |
Automated tests |
vendor/ |
Composer dependencies |
Laravel – Configuration
Laravel configuration files are stored in:
config/
Environment-specific values are generally stored in:
.env
For example:
APP_NAME=Laravel
APP_ENV=local
APP_DEBUG=true
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=example
DB_USERNAME=root
DB_PASSWORD=
Generate the application encryption key with:
php artisan key:generate
For production:
APP_DEBUG=false
Never commit sensitive .env values to source control.
Laravel – Routing
Routes define how Laravel responds to incoming HTTP requests.
Routes are commonly defined in:
routes/web.php
A basic route:
use Illuminate\Support\Facades\Route;
Route::get('/about', function () {
return 'About Us';
});
A controller route:
use App\Http\Controllers\UserController;
Route::get('/users', [
UserController::class,
'index',
]);
Named routes:
Route::get('/profile', [
UserController::class,
'profile',
])->name('profile');
Generate the URL with:
$url = route('profile');
View routes with:
php artisan route:list
Laravel – Middleware
Middleware filters incoming HTTP requests before they reach the application logic.
Create middleware with:
php artisan make:middleware CheckUserRole
A middleware can inspect or modify a request:
public function handle(Request $request, Closure $next): Response
{
if (!$request->user()) {
return redirect()->route('login');
}
return $next($request);
}
Middleware can be applied to routes:
Route::get('/dashboard', [
DashboardController::class,
'index',
])->middleware('auth');
Modern Laravel applications configure middleware in bootstrap/app.php.
Laravel – Controllers
Controllers organize application logic into dedicated classes.
Create a controller:
php artisan make:controller UserController
Example:
<?php
namespace App\Http\Controllers;
class UserController extends Controller
{
public function index()
{
return view('users.index');
}
}
Connect it to a route:
Route::get('/users', [
UserController::class,
'index',
]);
Resource controllers can be generated with:
php artisan make:controller ProductController --resource
Register resource routes:
Route::resource('products', ProductController::class);
Laravel – Views
Laravel views are generally stored in:
resources/views/
Blade templates use the .blade.php extension.
Example:
resources/views/users/index.blade.php
Return a view from a controller:
return view('users.index');
Pass data to a view:
return view('users.index', [
'users' => $users,
]);
In Blade:
@foreach ($users as $user)
<h2>{{ $user->name }}</h2>
@endforeach
Laravel – Blade Templates
Blade is Laravel’s templating engine.
A basic conditional:
@if ($user->isAdmin())
<p>Administrator</p>
@else
<p>Regular User</p>
@endif
A loop:
@foreach ($products as $product)
<p>{{ $product->name }}</p>
@endforeach
Layouts can be created with:
@extends('layouts.app')
@section('content')
<h1>Dashboard</h1>
@endsection
Blade automatically escapes:
{{ $value }}
Raw output can be rendered with:
{!! $value !!}
Use raw output only when the content is trusted.
Laravel – Request
Laravel’s Request object provides access to incoming HTTP request data.
use Illuminate\Http\Request;
public function store(Request $request)
{
$name = $request->input('name');
return response()->json([
'name' => $name,
]);
}
Other useful methods include:
$request->all();
$request->only(['name', 'email']);
$request->except(['password']);
$request->has('email');
$request->filled('email');
$request->method();
$request->url();
$request->query('page');
Laravel – Response
Laravel provides multiple ways to create HTTP responses.
Simple response:
return response('Hello Laravel');
JSON response:
return response()->json([
'name' => 'Sandeep',
'status' => 'active',
]);
Redirect:
return redirect()->route('dashboard');
Redirect with session data:
return redirect()
->route('users.index')
->with('success', 'User created successfully.');
Laravel – Redirections
Laravel provides several redirection methods.
Named route:
return redirect()->route('profile');
With parameters:
return redirect()->route('users.show', [
'user' => $user->id,
]);
Back to the previous page:
return back();
Redirect to an external URL:
return redirect()->away('https://example.com');
For external redirects, ensure the destination is trusted and appropriately controlled.
Laravel – Database
Laravel supports several relational database systems, including:
-
MySQL
-
MariaDB
-
PostgreSQL
-
SQLite
-
SQL Server
Database configuration is normally stored in .env.
Laravel provides three primary database access approaches:
-
Query Builder
-
Eloquent ORM
-
Raw SQL
Query Builder example:
$users = DB::table('users')
->where('status', 'active')
->get();
Eloquent example:
$users = User::where('status', 'active')->get();
Laravel – Migrations
Migrations provide version-controlled database schema changes.
Create a migration:
php artisan make:migration create_products_table
Example:
Schema::create('products', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->decimal('price', 10, 2);
$table->timestamps();
});
Run migrations:
php artisan migrate
Rollback the latest migration batch:
php artisan migrate:rollback
Laravel – Eloquent ORM
Eloquent provides an object-oriented interface for interacting with database tables.
Create a model:
php artisan make:model Product
Retrieve records:
$products = Product::all();
Find a record:
$product = Product::find(1);
Create a record:
$product = Product::create([
'name' => 'Laptop',
'price' => 75000,
]);
Update:
$product->update([
'price' => 70000,
]);
Delete:
$product->delete();
Laravel – Pagination
Laravel provides built-in pagination for Query Builder and Eloquent.
$users = User::paginate(15);
In Blade:
@foreach ($users as $user)
<p>{{ $user->name }}</p>
@endforeach
{{ $users->links() }}
Other pagination methods include:
User::simplePaginate(15);
and:
User::orderBy('id')->cursorPaginate(15);
Control the number of visible links:
$users = User::paginate(15)->onEachSide(2);
Laravel – Validation
Laravel provides convenient request validation.
$request->validate([
'name' => ['required', 'string', 'max:255'],
'email' => ['required', 'email'],
'password' => ['required', 'confirmed', 'min:8'],
]);
Display validation errors in Blade:
@error('email')
<p>{{ $message }}</p>
@enderror
For larger forms, use Form Request classes:
php artisan make:request StoreUserRequest
Laravel – Forms
Blade forms should include CSRF protection:
<form method="POST" action="{{ route('users.store') }}">
@csrf
<input
type="text"
name="name"
value="{{ old('name') }}"
>
<button type="submit">
Create User
</button>
</form>
For HTTP methods not directly supported by HTML forms:
@method('PUT')
or:
@method('DELETE')
Laravel – CSRF Protection
Laravel protects web forms against Cross-Site Request Forgery (CSRF) attacks.
Include the CSRF token in Blade forms:
<form method="POST">
@csrf
</form>
For JavaScript requests, the token can be sent using the X-CSRF-TOKEN header.
<meta
name="csrf-token"
content="{{ csrf_token() }}"
>
JavaScript:
const token = document
.querySelector('meta[name="csrf-token"]')
.getAttribute('content');
fetch('/users', {
method: 'POST',
headers: {
'X-CSRF-TOKEN': token,
'Content-Type': 'application/json',
},
body: JSON.stringify({
name: 'Sandeep'
})
});
Laravel – Authentication
Authentication verifies the identity of users.
Laravel authentication commonly involves:
-
Users
-
Guards
-
Providers
-
Sessions
-
Password hashing
-
Authentication middleware
Protect a route:
Route::get('/dashboard', [
DashboardController::class,
'index',
])->middleware('auth');
Check authentication:
if (auth()->check()) {
// User is authenticated.
}
Retrieve the authenticated user:
$user = auth()->user();
Logout:
Auth::logout();
After logout, applications should appropriately invalidate the session and regenerate the CSRF token.
Laravel – Authorization
Authentication answers:
Who is the user?
Authorization answers:
What is the user allowed to do?
Laravel provides Gates and Policies.
Create a policy:
php artisan make:policy PostPolicy --model=Post
Controller authorization:
$this->authorize('update', $post);
Blade:
@can('update', $post)
<a href="#">Edit</a>
@endcan
Laravel – Sessions
Sessions store data between requests.
Store data:
session([
'user_id' => 10,
]);
Retrieve it:
$userId = session('user_id');
Using the request session:
$request->session()->put('cart_total', 2500);
Retrieve:
$total = $request->session()->get('cart_total');
Flash data:
$request->session()->flash(
'success',
'Profile updated successfully.'
);
Laravel – Cookies
Create a cookie:
return response('Cookie created')
->cookie('theme', 'dark', 60);
Retrieve a cookie:
$theme = request()->cookie('theme');
Delete a cookie:
return response('Cookie removed')
->withoutCookie('theme');
Avoid storing sensitive information directly in client-controlled cookie values unless the appropriate Laravel protection mechanisms are being used.
Laravel – File Uploading
HTML forms uploading files must use:
<form
method="POST"
enctype="multipart/form-data"
>
@csrf
<input type="file" name="image">
<button type="submit">Upload</button>
</form>
Validate the upload:
$request->validate([
'image' => ['required', 'image', 'max:2048'],
]);
Store the file:
$path = $request->file('image')
->store('uploads', 'public');
Create the public storage link:
php artisan storage:link
Laravel – Sending Email
Laravel provides Mailables for email functionality.
Create one:
php artisan make:mail WelcomeMail
Send it:
use App\Mail\WelcomeMail;
use Illuminate\Support\Facades\Mail;
Mail::to($user->email)
->send(new WelcomeMail($user));
For high-volume applications, emails can be queued:
Mail::to($user->email)
->queue(new WelcomeMail($user));
Configure the mail service through .env.
Laravel – AJAX and Fetch Requests
Modern Laravel applications can use the browser’s native fetch() API.
Example:
fetch('/api/users')
.then(response => response.json())
.then(data => {
console.log(data);
});
A Laravel controller can return JSON:
return response()->json([
'message' => 'User created successfully',
]);
For POST requests to web routes, include CSRF protection as required.
Laravel – Error Handling
Laravel provides centralized exception handling and logging.
In development:
APP_DEBUG=true
In production:
APP_DEBUG=false
Manually report an exception:
report($exception);
Abort with an HTTP status code:
abort(404);
Custom error views can be placed in:
resources/views/errors/
For example:
resources/views/errors/404.blade.php
Laravel – Logging
Laravel provides a logging system based on configured logging channels.
use Illuminate\Support\Facades\Log;
Log::info('User logged in', [
'user_id' => $user->id,
]);
Warning:
Log::warning('Unexpected account activity', [
'user_id' => $user->id,
]);
Error:
Log::error('Payment processing failed', [
'order_id' => $order->id,
]);
Avoid logging passwords, tokens, API keys, or other sensitive information.
Laravel – Events
Events allow different parts of an application to communicate without tightly coupling the components.
Create an event:
php artisan make:event OrderPlaced
Create a listener:
php artisan make:listener SendOrderConfirmation --event=OrderPlaced
Dispatch an event:
OrderPlaced::dispatch($order);
Events are useful for tasks such as:
-
Sending notifications
-
Recording activity
-
Processing orders
-
Updating analytics
-
Triggering background jobs
Laravel – Queues and Jobs
Queues allow expensive tasks to run in the background.
Create a job:
php artisan make:job ProcessOrder
Dispatch it:
ProcessOrder::dispatch($order);
Start a queue worker:
php artisan queue:work
Queues are useful for:
-
Email delivery
-
Image processing
-
Report generation
-
API calls
-
Notifications
-
Large data processing
Laravel – Task Scheduling
Laravel’s scheduler allows recurring tasks to be defined in application code.
For example:
use Illuminate\Support\Facades\Schedule;
Schedule::command('reports:send')
->dailyAt('09:00');
Other examples:
Schedule::command('reports:send')->hourly();
Schedule::command('reports:send')->daily();
Schedule::command('reports:send')->weekly();
View scheduled tasks:
php artisan schedule:list
For local development:
php artisan schedule:work
Laravel – Artisan
Artisan is Laravel’s command-line interface.
View available commands:
php artisan list
Create a controller:
php artisan make:controller UserController
Create a model:
php artisan make:model Product
Clear optimization caches:
php artisan optimize:clear
Start the development server:
php artisan serve
Open Laravel’s interactive shell:
php artisan tinker
Create a custom command:
php artisan make:command ProcessOrders
Laravel – Encryption
Laravel provides application-level encryption through the Crypt facade and helper functions.
Encrypt a value:
use Illuminate\Support\Facades\Crypt;
$encrypted = Crypt::encryptString('Secret information');
Decrypt it:
$decrypted = Crypt::decryptString($encrypted);
The application encryption key is stored in:
APP_KEY=
Generate the key with:
php artisan key:generate
Encryption is reversible, unlike password hashing.
Laravel – Hashing
Password hashing is handled through Laravel’s Hash facade.
Hash a password:
use Illuminate\Support\Facades\Hash;
$hashed = Hash::make('password');
Verify it:
if (Hash::check('password', $hashed)) {
// Password is correct.
}
Hashing is designed to be one-way and should be used for passwords rather than encryption.
Laravel – Localization
Laravel supports multiple languages through translation files.
Translations are commonly stored in:
lang/
Example:
return [
'welcome' => 'Welcome to our application!',
];
Retrieve the translation:
__('messages.welcome');
Blade:
{{ __('messages.welcome') }}
Change the current locale:
app()->setLocale('fr');
Laravel – Facades
Facades provide convenient access to Laravel services.
Examples include:
Cache::get('key');
DB::table('users')->get();
Log::info('Application event');
Storage::put('file.txt', 'Content');
Mail::to($email)->send($mail);
Facades provide a concise syntax while Laravel resolves the underlying services through its service container.
Laravel – Contracts
Laravel contracts are interfaces that define expected behavior.
For example:
interface PaymentGateway
{
public function charge(float $amount): bool;
}
An implementation can then follow that contract:
class StripePaymentGateway implements PaymentGateway
{
public function charge(float $amount): bool
{
// Process payment.
return true;
}
}
Contracts are useful when applications need interchangeable implementations and clear dependency boundaries.
Laravel – Dependency Injection
Laravel’s service container automatically resolves many class dependencies.
For example:
public function store(
Request $request,
PaymentService $paymentService
) {
$paymentService->process();
return response()->json([
'message' => 'Payment processed',
]);
}
Dependency injection makes classes easier to test, maintain, and replace.
Laravel – Service Container
The service container manages class dependencies and application services.
Bind an interface:
$this->app->bind(
PaymentGateway::class,
StripePaymentGateway::class
);
Laravel can then resolve the interface automatically:
public function __construct(
PaymentGateway $paymentGateway
) {
$this->paymentGateway = $paymentGateway;
}
Laravel – Artisan Tinker
Tinker provides an interactive PHP shell for working with the Laravel application.
Start Tinker:
php artisan tinker
Retrieve users:
User::all();
Find a user:
User::find(1);
Create a model:
User::create([
'name' => 'Sandeep',
'email' => 'sandeep@example.com',
'password' => Hash::make('password'),
]);
Tinker is especially useful for development and troubleshooting.
Laravel – Testing
Laravel provides testing support for application code.
Run all tests:
php artisan test
Run a specific test:
php artisan test --filter UserTest
Feature tests can test complete application behavior:
public function test_users_page_is_available(): void
{
$response = $this->get('/users');
$response->assertStatus(200);
}
You can also test JSON responses:
$response = $this->getJson('/api/users');
$response->assertOk()
->assertJsonStructure([
'data',
]);
Laravel – Artisan Command Testing
Custom Artisan commands can also be tested.
$this->artisan('reports:send')
->expectsOutput('Reports sent successfully.')
->assertExitCode(0);
Interactive commands can be tested:
$this->artisan('user:greet')
->expectsQuestion('What is your name?', 'Sandeep')
->expectsOutput('Hello, Sandeep!')
->assertExitCode(0);
This allows command behavior to be verified without manually interacting with the terminal.
Laravel – Dump Server
Laravel provides debugging helpers such as:
dump($user);
and:
dd($user);
dump() displays information and continues execution.
dd() means Dump and Die and stops execution after displaying the value.
During development, the dump server can be started with:
php artisan dump-server
For production diagnostics, use Laravel’s logging system instead of debugging dumps.
Laravel – Action URL
Laravel’s action() helper can generate a URL for a controller action.
use App\Http\Controllers\PostController;
$url = action([
PostController::class,
'index',
]);
With parameters:
$url = action([
PostController::class,
'show',
], [
'id' => 10,
]);
For most application navigation, named routes are generally preferable:
$url = route('posts.show', [
'post' => 10,
]);
Laravel – File Storage
Laravel provides a filesystem abstraction through the Storage facade.
Store a file:
use Illuminate\Support\Facades\Storage;
Storage::put(
'documents/example.txt',
'Hello Laravel'
);
Check whether a file exists:
if (Storage::exists('documents/example.txt')) {
// File exists.
}
Delete a file:
Storage::delete('documents/example.txt');
Laravel can work with local storage and cloud storage services through configured filesystem disks.
Laravel – API Development
Laravel can be used to build JSON APIs.
Example route:
Route::get('/users', function () {
return response()->json(
User::latest()->paginate(15)
);
});
API controllers can return:
return response()->json([
'message' => 'User created successfully',
'user' => $user,
], 201);
For larger APIs, Laravel provides additional tools such as API resources for controlling the structure of JSON responses.
Laravel – Resource Controllers
Resource controllers provide conventional CRUD actions.
Generate one:
php artisan make:controller ProductController --resource
Register it:
Route::resource('products', ProductController::class);
The conventional actions are:
| Method | Purpose |
|---|---|
index() |
Display resources |
create() |
Display creation form |
store() |
Store new resource |
show() |
Display resource |
edit() |
Display edit form |
update() |
Update resource |
destroy() |
Delete resource |
Laravel – Route Model Binding
Laravel can automatically resolve route parameters into Eloquent models.
Route:
Route::get('/users/{user}', [
UserController::class,
'show',
]);
Controller:
use App\Models\User;
public function show(User $user)
{
return view('users.show', compact('user'));
}
Laravel automatically retrieves the corresponding User model.
This avoids repeatedly writing:
$user = User::findOrFail($id);
Laravel – Release and Upgrade Process
Laravel applications should be upgraded carefully.
Check the installed Laravel version:
php artisan --version
Review dependencies:
composer outdated
Before upgrading:
-
Read the upgrade documentation.
-
Review framework changes and deprecations.
-
Update dependencies carefully.
-
Run automated tests.
-
Test the application in staging.
-
Back up important data.
-
Deploy using a controlled process.
Avoid upgrading production applications without first testing the new dependency versions.
Laravel – Useful Artisan Reference
| Command | Purpose |
|---|---|
php artisan list |
List commands |
php artisan about |
Application information |
php artisan serve |
Start development server |
php artisan tinker |
Open interactive shell |
php artisan route:list |
List routes |
php artisan migrate |
Run migrations |
php artisan migrate:rollback |
Roll back migrations |
php artisan db:seed |
Run database seeders |
php artisan queue:work |
Process queued jobs |
php artisan schedule:list |
List scheduled tasks |
php artisan test |
Run tests |
php artisan optimize:clear |
Clear optimization caches |
php artisan config:cache |
Cache configuration |
php artisan route:cache |
Cache routes |
php artisan make:model |
Create model |
php artisan make:controller |
Create controller |
php artisan make:request |
Create Form Request |
php artisan make:middleware |
Create middleware |
php artisan make:migration |
Create migration |
php artisan make:command |
Create Artisan command |
php artisan make:job |
Create queued job |
php artisan make:event |
Create event |
php artisan make:listener |
Create listener |
php artisan make:mail |
Create mailable |
Laravel – Recommended Development Workflow
A typical Laravel development workflow can look like this:
1. Create the application
composer create-project laravel/laravel example-app
2. Configure environment variables
Edit:
.env
3. Generate the application key
php artisan key:generate
4. Configure the database
Set the appropriate database variables in .env.
5. Run migrations
php artisan migrate
6. Create application components
For example:
php artisan make:model Product -m
php artisan make:controller ProductController --resource
php artisan make:request StoreProductRequest
7. Define routes
Route::resource('products', ProductController::class);
8. Create Blade views
Store views under:
resources/views/
9. Validate incoming data
$request->validate([
'name' => ['required', 'string'],
]);
10. Test the application
php artisan test
11. Clear caches when necessary
php artisan optimize:clear
12. Build frontend assets when required
npm install
npm run build
Laravel – Quick Reference
Create a project
composer create-project laravel/laravel example-app
Start development server
php artisan serve
Create model and migration
php artisan make:model Product -m
Create controller
php artisan make:controller ProductController
Create resource controller
php artisan make:controller ProductController --resource
Create middleware
php artisan make:middleware CheckRole
Create Form Request
php artisan make:request StoreProductRequest
Run migrations
php artisan migrate
Start queue worker
php artisan queue:work
Run scheduler locally
php artisan schedule:work
Run tests
php artisan test
Open Tinker
php artisan tinker
Clear caches
php artisan optimize:clear
Summary
Laravel provides a complete ecosystem for building modern PHP web applications.
The core concepts include:
-
Routing for handling URLs and HTTP requests.
-
Controllers for organizing application logic.
-
Blade for server-rendered views.
-
Eloquent for database interaction.
-
Migrations for managing database structure.
-
Validation for protecting and verifying input.
-
Middleware for filtering requests.
-
Authentication and Authorization for application security.
-
Sessions and Cookies for maintaining state.
-
Queues and Jobs for background processing.
-
Events and Listeners for decoupled application workflows.
-
Mail and Notifications for communication.
-
File Storage for managing uploaded and generated files.
-
Caching for improving performance.
-
Task Scheduling for recurring operations.
-
Artisan for command-line development and administration.
-
Testing for verifying application behavior.
-
APIs for building integrations and modern web/mobile backends.
A typical Laravel application combines these components to create applications that are structured, maintainable, testable, and scalable.