Introduction
Laravel is one of the most popular PHP frameworks for developing modern web applications. It provides a clean development structure, built-in security features, database management tools, authentication support, and many other features that help developers build applications faster.
Whether you are a beginner learning PHP or an experienced developer looking to improve your web development skills, Laravel provides the tools you need to create everything from simple websites to complex business applications.
In this tutorial, you will learn Laravel 13 step by step, starting with installation and moving towards database operations, CRUD functionality, form validation, and application development.
By the end of this guide, you will understand the fundamentals of Laravel and have the knowledge needed to start building your own Laravel projects.
1. What Is Laravel?
Laravel is an open-source PHP web application framework designed to make web development easier and more efficient.
It follows the Model-View-Controller (MVC) architectural pattern, which separates an application into three main components:
Model: Handles database-related operations and application data.
View: Displays the user interface using Blade templates.
Controller: Handles requests, processes application logic, and returns responses.
Laravel provides several built-in features, including:
Clean routing system
Blade templating engine
Eloquent ORM
Database migrations
Form validation
Authentication and authorization
Middleware
REST API development
Task scheduling and queues
File uploads and storage
Security features
These features reduce repetitive coding and help developers maintain organized applications.
2. Requirements for Laravel 13
Before installing Laravel 13, make sure your development environment meets its requirements.
You generally need:
PHP version supported by Laravel 13
Composer
MySQL or another supported database
Node.js and npm when compiling frontend assets
Visual Studio Code or another code editor
A local development environment such as Laravel Herd, XAMPP, or a compatible PHP setup
You can check your installed PHP version using:
php -v
Check Composer:
composer -V
Check Node.js:
node -v
Check npm:
npm -v
Important: Laravel 13 has specific PHP and dependency requirements. Check the official Laravel 13 documentation before installing to confirm that your PHP version and environment are compatible.
3. How to Install Laravel 13
There are multiple ways to create a Laravel application. The following method uses Composer.
Step 1: Install Composer
Composer is a dependency manager for PHP. Laravel uses Composer to install its framework and other PHP packages.
Download Composer from:
After installation, verify it:
composer -V
Step 2: Create a Laravel Project
Open your terminal and execute:
composer create-project laravel/laravel my-laravel-app "^13.0"
This command creates a new Laravel project named my-laravel-app.
Move into the project directory:
cd my-laravel-app
Step 3: Start the Development Server
Run:
php artisan serve
You should see a local development URL in your terminal, usually:
Open this URL in your browser.
If the installation is successful, you should see the Laravel welcome page.
4. Understanding Laravel 13 Project Structure
When you create a Laravel application, the framework generates several folders and files.
Understanding the project structure is important before starting development.
Folder / File
Purpose
app/
Application logic, models, controllers, middleware
app/Models/
Eloquent models
app/Http/Controllers/
Application controllers
app/Http/Middleware/
Request middleware
bootstrap/
Framework bootstrapping and application configuration
config/
Configuration files
database/
Migrations, factories, and seeders
public/
Public entry point and public assets
resources/
Blade views and frontend source assets
routes/
Application route definitions
storage/
Logs, cache, and uploaded application files
tests/
Automated tests
vendor/
Composer-installed dependencies
.env
Environment-specific configuration
Some important files include:
routes/web.php: Defines routes for browser-based applications.
routes/api.php: Defines API routes when the API routing feature is installed or configured.
.env: Stores environment-specific settings such as database credentials.
composer.json: Defines PHP dependencies and Composer scripts.
artisan: Laravel's command-line interface.
bootstrap/app.php: Configures how the Laravel application is bootstrapped, including middleware and routing.
5. Understanding Laravel MVC Architecture
Laravel follows the MVC architecture.
Let's understand it using a simple example.
Imagine you are developing a blog application. When a visitor opens an article, the following process takes place:
The browser sends a request to Laravel.
Laravel identifies the matching route.
The route calls a controller.
The controller requests article data from the model.
The model retrieves the data from the database.
The controller sends the data to a Blade view.
The view displays the article in the browser.
The basic flow looks like this:
Browser Request
|
v
Route
|
v
Controller
|
v
Model
|
v
Database
|
v
Controller
|
v
Blade View
|
v
Browser Response
Separating these responsibilities makes applications easier to maintain and extend.
6. Understanding Laravel Routes
Routes define how Laravel responds to incoming HTTP requests.
Laravel's web routes are generally defined in:
routes/web.php
Basic Route
Open routes/web.php and add:
use Illuminate\Support\Facades\Route;
Route::get('/hello', function () {
return 'Hello, Laravel 13!';
});Open:
You will see the response:
Hello, Laravel 13!
Common HTTP Methods
Laravel supports several HTTP methods.
Method
Purpose
GET
Retrieve information
POST
Submit or create information
PUT
Replace or update information
PATCH
Partially update information
DELETE
Delete information
Example:
Route::get('/users', function () {
return 'Display users';
});
Route::post('/users', function () {
return 'Create user';
});
Route::put('/users/{id}', function ($id) {
return 'Update user ' . $id;
});
Route::delete('/users/{id}', function ($id) {
return 'Delete user ' . $id;
});Route Parameters
You can pass dynamic values through routes.
Route::get('/users/{id}', function ($id) {
return 'User ID: ' . $id;
});For example:
/users/10
The output will be:
User ID: 10
Named Routes
Named routes allow you to refer to routes using a name instead of hardcoding their URLs.
Route::get('/about-us', function () {
return view('about');
})->name('about');You can generate the URL using:
route('about');Named routes are useful when URLs change because you do not need to update every reference manually.
7. Creating Controllers in Laravel
Controllers organize application logic and handle incoming requests.
You can create a controller using Artisan:
php artisan make:controller UserController
Laravel creates the controller inside:
app/Http/Controllers/UserController.php
Open the file and add:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class UserController extends Controller
{
public function index()
{
return 'User List';
}
public function show($id)
{
return 'User ID: ' . $id;
}
}Now define the routes:
use App\Http\Controllers\UserController;
Route::get('/users', [UserController::class, 'index']);
Route::get('/users/{id}', [UserController::class, 'show']);When you visit /users, Laravel executes the index() method.
When you visit /users/5, Laravel executes the show() method with the ID value of 5.
8. Understanding Blade Templates
Blade is Laravel's built-in templating engine. It helps developers create dynamic HTML pages using reusable templates and simple syntax.
Blade files are stored in:
resources/views/
Create a file:
resources/views/home.blade.php
Add the following code:
<!DOCTYPE html>
<html>
<head>
<title>Laravel 13 Tutorial</title>
</head>
<body>
<h1>Welcome to Laravel 13</h1>
<p>This is my first Blade template.</p></body>
</html>
Return this view from a route:
Route::get('/home', function () {
return view('home');
});Passing Data to Blade
You can pass variables from a controller to a Blade view.
Controller:
public function index()
{
$name = 'Karthikeyan';
return view('home', compact('name'));
}Blade:
<h1>Welcome, {{ $name }}</h1>Blade Conditional Statements
@if($age >= 18)
<p>You are eligible.</p>
@else
<p>You are not eligible.</p>
@endifBlade Loops
@foreach($users as $user)
<p>{{ $user->name }}</p>
@endforeachBlade also supports layouts, components, sections, includes, and reusable UI elements.
9. Connecting MySQL Database with Laravel
Laravel supports multiple database systems, including MySQL.
To configure MySQL, open the .env file in your project root.
Update the database settings:
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel13_db
DB_USERNAME=root
DB_PASSWORD=
Create a database named laravel13_db in phpMyAdmin or MySQL.
Then clear the configuration cache:
php artisan config:clear
Your Laravel application can now connect to the configured database, provided the credentials and MySQL service are correct.
10. What Are Laravel Migrations?
Migrations allow developers to create and modify database tables using PHP code.
Instead of manually creating every table in phpMyAdmin, you can manage database structure through migration files.
Create a migration:
php artisan make:migration create_students_table
Open the generated migration inside:
database/migrations/
Add the table structure:
public function up(): void
{
Schema::create('students', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string('email')->unique();
$table->string('phone')->nullable();
$table->timestamps();
});
}Run the migration:
php artisan migrate
Laravel creates the students table in your database.
Common Migration Commands
php artisan migrate
Runs pending migrations.
php artisan migrate:rollback
Rolls back the latest migration batch.
php artisan migrate:status
Displays migration status.
Note: Be careful when using migration reset or fresh commands in production because they can delete existing tables and data.
11. Understanding Laravel Models and Eloquent ORM
Models represent database tables and allow you to work with database records using PHP.
Create a Student model:
php artisan make:model Student
Laravel creates:
app/Models/Student.php
Example:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Student extends Model
{
protected $fillable = [
'name',
'email',
'phone'
];
}The $fillable property defines which attributes can be mass assigned.
Retrieving Records
$students = Student::all();
Finding a Record
$student = Student::find(1);
Inserting a Record
Student::create([
'name' => 'Arun',
'email' => 'arun@example.com',
'phone' => '9876543210'
]);Updating a Record
$student = Student::findOrFail(1);
$student->update([
'name' => 'Arun Kumar'
]);Deleting a Record
$student = Student::findOrFail(1); $student->delete();
Eloquent makes database operations easier and provides support for relationships, scopes, events, accessors, and more.
12. Building a Simple CRUD Application in Laravel 13
CRUD stands for:
Create
Read
Update
Delete
These are the four basic operations used in most database-driven applications.
Let's build a simple Student Management module.
Step 1: Create Model and Migration
Run:
php artisan make:model Student -m
Update the generated migration:
public function up(): void
{
Schema::create('students', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string('email')->unique();
$table->string('phone')->nullable();
$table->timestamps();
});
}Run:
php artisan migrate
Step 2: Configure the Model
Open app/Models/Student.php:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Student extends Model
{
protected $fillable = [
'name',
'email',
'phone'
];
}Step 3: Create a Resource Controller
Run:
php artisan make:controller StudentController --resource
A resource controller provides methods for common CRUD operations.
Step 4: Add Controller Logic
Open StudentController.php:
<?php
namespace App\Http\Controllers;
use App\Models\Student;
use Illuminate\Http\Request;
class StudentController extends Controller
{
public function index()
{
$students = Student::latest()->paginate(10);
return view('students.index', compact('students'));
}
public function create()
{
return view('students.create');
}
public function store(Request $request)
{
$validated = $request->validate([
'name' => 'required|string|max:255',
'email' => 'required|email|unique:students,email',
'phone' => 'nullable|string|max:20'
]);
Student::create($validated);
return redirect()
->route('students.index')
->with('success', 'Student created successfully.');
}
public function show(Student $student)
{
return view('students.show', compact('student'));
}
public function edit(Student $student)
{
return view('students.edit', compact('student'));
}
public function update(Request $request, Student $student)
{
$validated = $request->validate([
'name' => 'required|string|max:255',
'email' => 'required|email|unique:students,email,' . $student->id,
'phone' => 'nullable|string|max:20'
]);
$student->update($validated);
return redirect()
->route('students.index')
->with('success', 'Student updated successfully.');
}
public function destroy(Student $student)
{
$student->delete();
return redirect()
->route('students.index')
->with('success', 'Student deleted successfully.');
}
}Step 5: Define Resource Routes
In routes/web.php:
use App\Http\Controllers\StudentController;
Route::resource('students', StudentController::class);This creates routes for listing, creating, storing, viewing, editing, updating, and deleting students.
You can inspect them using:
php artisan route:list
Step 6: Create Blade Views
Create this folder:
resources/views/students/
<h1>Student List</h1>
<a href="{{ route('students.create') }}">Add Student</a>
@if(session('success'))
<p>{{ session('success') }}</p>
@endif
<table border="1" cellpadding="10">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Email</th>
<th>Phone</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
@foreach($students as $student)
<tr>
<td>{{ $student->id }}</td>
<td>{{ $student->name }}</td>
<td>{{ $student->email }}</td>
<td>{{ $student->phone }}</td>
<td>
<a href="{{ route('students.edit', $student->id) }}">Edit</a>
<form action="{{ route('students.destroy', $student->id) }}"
method="POST"
style="display:inline;">
@csrf
@method('DELETE')
<button type="submit">Delete</button>
</form>
</td>
</tr>
@endforeach
</tbody>
</table>
{{ $students->links() }}<h1>Add Student</h1>
<form action="{{ route('students.store') }}" method="POST">
@csrf
<div>
<label>Name</label>
<input type="text" name="name" value="{{ old('name') }}">
@error('name')
<p>{{ $message }}</p>
@enderror
</div>
<div>
<label>Email</label>
<input type="email" name="email" value="{{ old('email') }}">
@error('email')
<p>{{ $message }}</p>
@enderror
</div>
<div>
<label>Phone</label>
<input type="text" name="phone" value="{{ old('phone') }}">
@error('phone')
<p>{{ $message }}</p>
@enderror
</div>
<button type="submit">Save Student</button>
</form>For a complete working CRUD module, you should also create the edit.blade.php and show.blade.php views. The edit form should submit to students.update using @method('PUT') and include @csrf.
You can improve the interface by using Bootstrap 5 forms, tables, alerts, and responsive layouts.
13. Form Validation in Laravel
Form validation ensures that users submit valid information.
Laravel provides a simple validation system.
Example:
$request->validate([
'name' => 'required|string|max:255',
'email' => 'required|email',
'password' => 'required|min:8'
]);Some commonly used validation rules are:
Rule
Purpose
required
Field must contain a value
Must be a valid email address
min:8
Minimum length of 8
max:255
Maximum length of 255
unique:users,email
Value must be unique in the specified column
numeric
Must contain a numeric value
nullable
Field may be empty
confirmed
Must match its confirmation field
image
Must be a valid image file
Displaying Validation Errors in Blade
@error('email')
<span class="text-danger">{{ $message }}</span>
@enderrorLaravel automatically redirects back with validation errors when validation fails for a traditional web form.
14. Middleware in Laravel
Middleware acts as a layer between incoming requests and your application.
It can inspect requests and decide whether they should continue.
Common uses include:
Authentication checks
Role-based access
Request filtering
Logging
Rate limiting
Security restrictions
php artisan make:middleware CheckUserRole
Example:
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;
class CheckUserRole
{
public function handle(Request $request, Closure $next): Response
{
if (!auth()->check() || auth()->user()->role !== 'admin') {
abort(403);
}
return $next($request);
}
}In modern Laravel applications, middleware aliases are registered in:
bootstrap/app.php
You can then apply the registered alias to protected routes.
Important: This is a basic example. Real applications should use proper authentication, authorization policies, and role permissions rather than relying on a single role check everywhere.
15. Authentication in Laravel
Authentication verifies the identity of a user before allowing access to protected parts of an application.
Common authentication features include:
User registration
Login
Logout
Password reset
Email verification
Remember me
Session management
Laravel provides starter kits to help implement authentication.
You can also build custom authentication using Laravel's authentication services and session features.
For production applications, use a maintained authentication starter kit compatible with your Laravel version, configure password resets securely, and protect authenticated routes with the appropriate middleware.
16. File Uploads in Laravel
Laravel makes file uploads straightforward.
Example controller method:
public function upload(Request $request)
{
$request->validate([
'image' => 'required|image|mimes:jpg,jpeg,png,webp|max:2048'
]);
$path = $request->file('image')->store('students', 'public');
return back()->with('success', 'Image uploaded successfully.');
}Create a symbolic link for public storage:
php artisan storage:link
The uploaded file will be stored under the configured public storage disk.
For production, validate file type and size, use generated filenames, and ensure the upload directory cannot execute uploaded scripts.
17. Laravel API Development
Laravel can be used to create REST APIs for mobile applications, web applications, and third-party integrations.
An API allows applications to communicate using HTTP requests and structured responses, commonly JSON.
Example API route:
use Illuminate\Support\Facades\Route;
Route::get('/students', function () {
return response()->json([
'status' => true,
'message' => 'Students retrieved successfully',
'data' => [
[
'id' => 1,
'name' => 'Arun'
],
[
'id' => 2,
'name' => 'Kumar'
]
]
]);
});Depending on your Laravel 13 application setup, API routing may need to be installed or enabled first.
For real applications, use controllers, request validation, API resources, and appropriate authentication.
Laravel Sanctum is a popular option for API token authentication and supported SPA authentication workflows.
18. Laravel Eloquent Relationships
Eloquent supports database relationships that allow you to connect related models.
The most common relationship types are:
One-to-One
One-to-Many
Many-to-Many
Has-One-Through
Has-Many-Through
Polymorphic relationships
One-to-Many Relationship
Imagine a blog application where one user can publish multiple posts.
In the User model:
public function posts()
{
return $this->hasMany(Post::class);
}In the Post model:
public function user()
{
return $this->belongsTo(User::class);
}Retrieve all posts belonging to a user:
$user = User::find(1); $posts = $user->posts;
Retrieve the author of a post:
$post = Post::find(1); $author = $post->user;
Relationships make it easier to retrieve related information without manually writing complex SQL queries for every operation.
19. Important Laravel Artisan Commands
Artisan is Laravel's command-line interface.
Developers use Artisan to generate files, manage migrations, clear caches, and perform many development tasks.
Command
Purpose
php artisan serve
Starts the local development server
php artisan list
Lists available Artisan commands
php artisan route:list
Displays registered routes
php artisan make:controller UserController
Creates a controller
php artisan make:model User
Creates a model
php artisan make:model Post -m
Creates a model and migration
php artisan make:migration create_posts_table
Creates a migration
php artisan make:middleware CheckRole
Creates middleware
php artisan migrate
Runs migrations
php artisan migrate:rollback
Rolls back the latest migration batch
php artisan db:seed
Runs database seeders
php artisan optimize:clear
Clears Laravel's optimization caches
You can explore all available commands using:
php artisan list
20. Laravel Security Best Practices
Security is an important part of every web application.
Follow these practices when developing Laravel applications:
Never expose your .env file publicly.
Keep APP_DEBUG=false in production.
Use Laravel's CSRF protection for web forms.
Validate all user input.
Use Eloquent or parameterized queries instead of unsafe SQL concatenation.
Use Blade's escaped output syntax ({{ }}) for untrusted content.
Protect administrative routes with authentication and authorization.
Apply rate limiting to sensitive endpoints.
Validate uploaded files and restrict permitted file types.
Store passwords using Laravel's hashing facilities.
Keep Laravel and Composer dependencies updated.
Use HTTPS for production websites.
Back up your database and important files regularly.
Following these practices helps protect your application and user information.
21. Deploying a Laravel Application to Shared Hosting
After completing development, you may want to publish your Laravel application online.
Laravel can run on compatible shared hosting environments, provided the hosting plan supports the required PHP version, extensions, Composer dependencies, and application configuration.
A typical deployment process includes:
Purchase a domain and suitable hosting plan.
Upload the Laravel project to a directory outside the publicly accessible web root.
Install production Composer dependencies.
Configure the .env file with production database credentials.
Create the MySQL database and user.
Run migrations carefully.
Configure the domain's document root to point to Laravel's public directory.
Set correct permissions for storage and bootstrap/cache.
Set APP_ENV=production.
Set APP_DEBUG=false.
Configure HTTPS.
Test routes, forms, database operations, uploads, and email delivery.
If your hosting provider only allows public_html as the document root, configure the application carefully so that only Laravel's public files are accessible from the web.
Never place the entire Laravel project inside a publicly accessible directory without proper protection.
22. Laravel 13 vs Core PHP
Beginners often wonder whether they should learn Core PHP or Laravel first.
Both are useful, but they serve different purposes.
Core PHP
Laravel
Requires more manual coding
Provides built-in development features
Developers organize architecture themselves
Provides a structured application architecture
Database queries are often written manually
Eloquent ORM simplifies database operations
Authentication must be implemented separately
Provides authentication tools and starter kits
Validation needs to be implemented manually or with libraries
Includes built-in validation
Reusable structure depends on developer design
Provides routing, controllers, Blade, and other conventions
Suitable for learning PHP fundamentals
Suitable for structured, maintainable web applications
Recommendation: Learn PHP fundamentals, object-oriented programming, MySQL, and MVC concepts before moving into advanced Laravel development.
23. What Projects Can You Build Using Laravel?
Once you understand Laravel fundamentals, you can start building practical applications.
Here are some project ideas:
Beginner Projects
Student Management System
Employee Management System
Personal Blog Website
Contact Management Application
Simple Task Management System
Intermediate Projects
School Management System
Hotel Booking System
Online Examination System
Inventory Management System
Customer Relationship Management (CRM)
Advanced Projects
Multi-vendor E-commerce Platform
Matrimony Website
Subscription-Based SaaS Application
Online Learning Management System
API-Based Mobile Application Backend
Building real projects is one of the best ways to improve your Laravel development skills.
24. Frequently Asked Questions About Laravel 13
1. Is Laravel 13 suitable for beginners?
Yes. Laravel 13 can be learned by beginners who understand basic PHP, HTML, CSS, and MySQL. Start with routes, controllers, Blade templates, and database migrations before moving to advanced topics.
2. Is Laravel free to use?
Yes. Laravel is an open-source PHP framework. You can use it to develop personal, commercial, and client projects. Hosting, paid services, and optional third-party packages may have separate costs.
3. Do I need to learn Core PHP before Laravel?
You should understand PHP fundamentals before learning Laravel. Knowledge of variables, functions, arrays, OOP, sessions, and database operations will make Laravel much easier to understand.
4. Which database is best for Laravel?
Laravel supports multiple databases. MySQL is a popular choice for web applications, especially for developers working with PHP-based hosting environments.
5. Can I build REST APIs using Laravel 13?
Yes. Laravel supports REST API development. You can use controllers, validation, JSON responses, API resources, and authentication tools such as Laravel Sanctum.
6. Can I host Laravel 13 on shared hosting?
Yes, if the hosting environment meets Laravel's PHP and extension requirements and supports the necessary deployment configuration. Shared hosting limitations may affect queues, scheduled tasks, and other background processes.
7. Is Laravel better than Core PHP?
Laravel offers built-in tools and a structured architecture that can make larger applications easier to develop and maintain. Core PHP is still useful for learning fundamentals and building smaller applications.
8. How long does it take to learn Laravel?
The time depends on your PHP background and practice. Someone familiar with PHP and MySQL may understand Laravel fundamentals in a few weeks. Building confidence with real-world applications takes more practice.
Conclusion
Laravel 13 is a powerful PHP framework for developing modern, secure, and maintainable web applications.
In this tutorial, we covered the fundamentals of Laravel, including installation, project structure, MVC architecture, routes, controllers, Blade templates, MySQL configuration, migrations, Eloquent ORM, CRUD operations, validation, middleware, authentication, file uploads, REST APIs, and deployment.
The best way to learn Laravel is to practise each topic by building small projects. Start with a CRUD application, then move on to authentication, API development, and complete business applications.
Keep practising, explore the official documentation, and gradually develop your own Laravel projects.
Need a Laravel website or custom web application?
2K Web Solutions provides PHP and Laravel web development services, including custom websites, admin panels, REST APIs, business applications, and database-driven solutions.
Visit 2K Web Solutions to explore web development services or contact us to discuss your project.
Useful Resources:
Laravel Official Documentation: https://laravel.com/docs/13.x
PHP Official Documentation: https://www.php.net/docs.php
Composer: https://getcomposer.org/
MySQL Documentation: https://dev.mysql.com/doc/