- We offer certified developers to hire.
- We’ve performed 500+ Web/App/eCommerce projects.
- Our clientele is 1000+.
- Free quotation on your project.
- We sign NDA for the security of your projects.
- Three months warranty on code developed by us.
Laravel is one of the most popular PHP frameworks, known for its elegant syntax, robust features, and ease of use. It follows the Model-View-Controller (MVC) architectural pattern and provides built-in tools for routing, authentication, caching, and database management.
In this first part, we will cover:
Laravel is an open-source PHP framework designed for developing modern web applications. It simplifies tasks like routing, authentication, and database interactions, making development faster and more efficient. Taylor Otwell created Laravel in 2011 as an alternative to the CodeIgniter framework, which lacked built-in features like authentication and routing.
Laravel is widely used due to its advantages over other PHP frameworks. Here’s why Laravel is a great choice:
Laravel’s syntax is clean and expressive, making it easy for developers to read and write code efficiently.
Unlike raw PHP or other frameworks that require manual implementations, Laravel provides built-in functionalities like authentication, database migrations, and templating.
Laravel supports caching, database indexing, and job queues, making it suitable for both small and large applications.
Laravel follows the MVC pattern, ensuring a clear separation between business logic, presentation, and data management.
Laravel provides CSRF (Cross-Site Request Forgery) protection, password hashing, SQL injection prevention, and encryption.
With a vast community of developers and regular updates, Laravel remains a robust framework with extensive documentation.
Before installing Laravel, ensure your system has the following requirements:
Laravel requires PHP 8.0 or higher. Check if PHP is installed using:
php -v
If PHP is not installed, download and install it from php.net.
Composer is a dependency manager for PHP, required for Laravel installation. Download and install Composer from getcomposer.org.
Verify the installation by running:
composer -V
Once PHP and Composer are installed, install Laravel globally using:
composer global require laravel/installer
Alternatively, create a Laravel project using:
composer create-project –prefer-dist laravel/laravel project-name
Laravel uses a .env file for environment configuration. Important settings include:
APP_NAME=LaravelApp
APP_ENV=local
APP_KEY=base64:your-generated-key
APP_DEBUG=true
APP_URL=http://localhost
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel_db
DB_USERNAME=root
DB_PASSWORD=
Modify the database credentials according to your MySQL setup.
Laravel has a well-structured directory system. Below is an overview of the key directories:
Contains the application startup script and cache folder for performance optimization.
Contains all configuration files, such as app.php, database.php, and auth.php.
Includes migrations, factories, and seeders for managing database structure.
Stores assets like images, JavaScript, and CSS files. The index.php file serves as the entry point for requests.
Used for logs, cache, and file uploads.
Contains unit and feature test cases.
After setting up Laravel, navigate to your project directory:
cd project-name
Start the Laravel development server using:
php artisan serve
You should see output similar to:
Laravel development server started: http://127.0.0.1:8000
Open http://127.0.0.1:8000 in your browser to view your Laravel project.
In Part 1, we set up our Laravel development environment and understood the basic directory structure. Now, in Part 2, we will focus on the core building blocks of a Laravel application:
By the end of this section, you’ll be able to create routes, controllers, and dynamic views in Laravel.
In Laravel, routing determines how the application responds to incoming HTTP requests. Laravel routes are defined in the routes/web.php file for web-based applications and routes/api.php for API applications.
Laravel supports different types of routes, including:
A simple route can be defined in routes/web.php:
use Illuminate\Support\Facades\Route;
Route::get(‘/hello’, function () {
return “Hello, Laravel!”;
});
You can pass dynamic values in routes:
Route::get(‘/user/{name}’, function ($name) {
return “Welcome, ” . $name;
});
You can also make parameters optional:
Route::get(‘/user/{name?}’, function ($name = “Guest”) {
return “Welcome, ” . $name;
});
Named routes are useful when generating URLs dynamically:
Route::get(‘/dashboard’, function () {
return view(‘dashboard’);
})->name(‘dashboard’);
Now, you can generate a URL for this route using:
$url = route(‘dashboard’);
To organize routes, Laravel allows grouping:
Route::prefix(‘admin’)->group(function () {
Route::get(‘/dashboard’, function () {
return “Admin Dashboard”;
});
Route::get(‘/users’, function () {
return “Manage Users”;
});
});
For CRUD operations, Laravel provides resource routes:
Route::resource(‘posts’, PostController::class);
This single line automatically creates routes for:
Controllers handle logic and allow separation of concerns.
Use the Artisan command to create a controller:
php artisan make:controller PageController
This will create a file in app/Http/Controllers/PageController.php.
Edit PageController.php and add methods:
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class PageController extends Controller
{
public function home()
{
return view(‘home’);
}
public function about()
{
return view(‘about’);
}
}
Now, define routes to use this controller:
use App\Http\Controllers\PageController;
Route::get(‘/’, [PageController::class, ‘home’]);
Route::get(‘/about’, [PageController::class, ‘about’]);
Now, Laravel will call PageController@home when you visit / and PageController@about when you visit /about.
You can pass dynamic data from controllers to views.
public function home()
{
$title = “Welcome to My Website”;
return view(‘home’, compact(‘title’));
}
In the home.blade.php file:
<h1>{{ $title }}</h1>
public function about()
{
return view(‘about’)->with(‘message’, ‘About Us Page’);
}
Inside about.blade.php:
<p>{{ $message }}</p>
Blade is Laravel’s built-in templating engine that helps separate logic from UI.
Create a base layout in resources/views/layouts/app.blade.php:
<!DOCTYPE html>
<html lang=”en”>
<head>
<title>@yield(‘title’)</title>
</head>
<body>
<header>
<h1>My Website</h1>
</header>
<div class=”content”>
@yield(‘content’)
</div>
</body>
</html>
Now, create a home.blade.php file inside resources/views/:
@extends(‘layouts.app’)
@section(‘title’, ‘Home Page’)
@section(‘content’)
<h2>Welcome to Laravel</h2>
<p>This is the homepage.</p>
@endsection
This will use the layout and insert the content inside @yield(‘content’).
@if($user == ‘admin’)
<p>Welcome, Admin!</p>
@else
<p>Welcome, Guest!</p>
@endif
@foreach($users as $user)
<p>{{ $user }}</p>
@endforeach
In Part 2, we covered Laravel routing, controllers, and the Blade templating engine. Now, in Part 3, we will focus on databases and Laravel’s Eloquent ORM, which allows you to interact with databases easily.
Laravel uses .env (environment file) to manage database configurations. Before using a database, we must configure it.
Open the .env file in the Laravel project root and update the following lines:
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel_db
DB_USERNAME=root
DB_PASSWORD=
After this, run:
php artisan config:clear
php artisan migrate
This will apply any pending database migrations.
Migrations are a way to create and modify database tables programmatically.
To create a new migration for a posts table, run:
php artisan make:migration create_posts_table
This creates a new migration file inside database/migrations/. Open the file and modify the up() method:
public function up()
{
Schema::create(‘posts’, function (Blueprint $table) {
$table->id();
$table->string(‘title’);
$table->text(‘content’);
$table->timestamps();
});
}
Now, run the migration to create the table:
php artisan migrate
This will generate a posts table in the database.
If you need to undo the last migration, use:
php artisan migrate:rollback
To rollback all migrations and re-run them:
php artisan migrate:fresh
Eloquent is Laravel’s ORM (Object-Relational Mapper), making database interactions easy.
To create a model for the posts table, run:
php artisan make:model Post
This creates app/Models/Post.php. Open the file and define the table structure:
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
use HasFactory;
protected $fillable = [‘title’, ‘content’];
}
Here, $fillable defines the columns we can insert/update in the database.
Now that we have a Post model, let’s see how to interact with the database.
We can create new records using Eloquent’s create() method:
use App\Models\Post;
Post::create([
‘title’ => ‘My First Post’,
‘content’ => ‘This is the content of my first post.’
]);
Alternatively, you can insert data like this:
$post = new Post();
$post->title = “Second Post”;
$post->content = “This is another post.”;
$post->save();
To fetch all posts:
$posts = Post::all();
foreach ($posts as $post) {
echo $post->title . “<br>”;
}
To fetch a single post by ID:
$post = Post::find(1);
echo $post->title;
To filter posts:
$posts = Post::where(‘title’, ‘like’, ‘%Laravel%’)->get();
To update a post:
$post = Post::find(1);
$post->title = “Updated Title”;
$post->save();
Alternatively, use:
Post::where(‘id’, 1)->update([‘title’ => ‘Updated Title’]);
To delete a post:
$post = Post::find(1);
$post->delete();
Or use:
Post::where(‘id’, 1)->delete();
To delete all records:
Post::truncate();
Laravel provides seeders and factories to insert dummy data into the database for testing.
Run the command:
php artisan make:seeder PostSeeder
Open database/seeders/PostSeeder.php and modify the run() method:
use Illuminate\Database\Seeder;
use App\Models\Post;
class PostSeeder extends Seeder
{
public function run()
{
Post::create([
‘title’ => ‘Seeder Post’,
‘content’ => ‘This post was inserted using a seeder.’
]);
}
}
To execute the seeder:
php artisan db:seed –class=PostSeeder
Factories help create multiple dummy records quickly.
First, generate a factory:
php artisan make:factory PostFactory
Modify database/factories/PostFactory.php:
use App\Models\Post;
use Illuminate\Database\Eloquent\Factories\Factory;
class PostFactory extends Factory
{
protected $model = Post::class;
public function definition()
{
return [
‘title’ => $this->faker->sentence,
‘content’ => $this->faker->paragraph,
];
}
}
Now, modify the run() method in PostSeeder:
Post::factory()->count(10)->create();
Run:
php artisan db:seed –class=PostSeeder
This will insert 10 random posts into the database.
In Part 3, we learned how to connect a database, use migrations, and work with Eloquent ORM. Now, in Part 4, we will focus on authentication and CRUD (Create, Read, Update, Delete) operations in Laravel.
Laravel provides built-in authentication features that make it easy to handle user logins and registrations. The easiest way to implement authentication is by using Laravel Breeze.
First, install Laravel Breeze using Composer:
composer require laravel/breeze –dev
After installation, run the following command to set up authentication:
php artisan breeze:install
This will install basic authentication views and routes. Next, migrate the database to create the users table:
php artisan migrate
Now, start the development server:
php artisan serve
Visit http://127.0.0.1:8000/register to create a new user account. Once registered, you can log in using http://127.0.0.1:8000/login.
Now, let’s build a CRUD (Create, Read, Update, Delete) system for managing posts.
Open routes/web.php and define the necessary routes:
use App\Http\Controllers\PostController;
Route::get(‘/posts’, [PostController::class, ‘index’])->name(‘posts.index’);
Route::get(‘/posts/create’, [PostController::class, ‘create’])->name(‘posts.create’);
Route::post(‘/posts’, [PostController::class, ‘store’])->name(‘posts.store’);
Route::get(‘/posts/{id}/edit’, [PostController::class, ‘edit’])->name(‘posts.edit’);
Route::put(‘/posts/{id}’, [PostController::class, ‘update’])->name(‘posts.update’);
Route::delete(‘/posts/{id}’, [PostController::class, ‘destroy’])->name(‘posts.destroy’);
Generate a controller using Artisan:
php artisan make:controller PostController
Now, open app/Http/Controllers/PostController.php and add the following methods:
use App\Models\Post;
use Illuminate\Http\Request;
class PostController extends Controller
{
public function index()
{
$posts = Post::all();
return view(‘posts.index’, compact(‘posts’));
}
}
public function create()
{
return view(‘posts.create’);
}
public function store(Request $request)
{
$request->validate([
‘title’ => ‘required|string|max:255’,
‘content’ => ‘required|string’,
]);
Post::create([
‘title’ => $request->title,
‘content’ => $request->content,
]);
return redirect()->route(‘posts.index’)->with(‘success’, ‘Post created successfully!’);
}
public function edit($id)
{
$post = Post::findOrFail($id);
return view(‘posts.edit’, compact(‘post’));
}
public function update(Request $request, $id)
{
$request->validate([
‘title’ => ‘required|string|max:255’,
‘content’ => ‘required|string’,
]);
$post = Post::findOrFail($id);
$post->update([
‘title’ => $request->title,
‘content’ => $request->content,
]);
return redirect()->route(‘posts.index’)->with(‘success’, ‘Post updated successfully!’);
}
public function destroy($id)
{
$post = Post::findOrFail($id);
$post->delete();
return redirect()->route(‘posts.index’)->with(‘success’, ‘Post deleted successfully!’);
}
To restrict access to certain pages, we can use middleware to ensure only authenticated users can access them.
Modify the routes in web.php:
Route::middleware([‘auth’])->group(function () {
Route::get(‘/posts’, [PostController::class, ‘index’])->name(‘posts.index’);
Route::get(‘/posts/create’, [PostController::class, ‘create’])->name(‘posts.create’);
Route::post(‘/posts’, [PostController::class, ‘store’])->name(‘posts.store’);
Route::get(‘/posts/{id}/edit’, [PostController::class, ‘edit’])->name(‘posts.edit’);
Route::put(‘/posts/{id}’, [PostController::class, ‘update’])->name(‘posts.update’);
Route::delete(‘/posts/{id}’, [PostController::class, ‘destroy’])->name(‘posts.destroy’);
});
Now, if an unauthenticated user tries to access any of these routes, they will be redirected to the login page.
To prevent invalid data from being submitted, we use Laravel’s built-in validation system.
In store() and update() methods, we already added validation:
$request->validate([
‘title’ => ‘required|string|max:255’,
‘content’ => ‘required|string’,
]);
If validation fails, Laravel will automatically redirect back with error messages.
Modify posts/create.blade.php:
@if ($errors->any())
<div class=”alert alert-danger”>
<ul>
@foreach ($errors->all() as $error)
<li>{{ $error }}</li>
@endforeach
</ul>
</div>
@endif
This will display errors if any field is invalid.
Flash messages help users see feedback messages like “Post created successfully!”.
Modify posts/index.blade.php:
@if (session(‘success’))
<div class=”alert alert-success”>
{{ session(‘success’) }}
</div>
@endif
Now, every time a post is created, updated, or deleted, the success message will appear.
In Part 4, we implemented authentication, a CRUD system, and route protection using middleware. Now, in Part 5, we will focus on:
A good UI improves user experience. We will integrate Bootstrap into our Laravel project for better styling.
Open resources/views/layouts/app.blade.php and add the Bootstrap CDN in the <head> section:
<!DOCTYPE html>
<html lang=”en”>
<head>
<meta charset=”UTF-8″>
<meta name=”viewport” content=”width=device-width, initial-scale=1″>
<title>Laravel Blog</title>
<link href=”https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css” rel=”stylesheet”>
</head>
<body>
<div class=”container mt-4″>
@yield(‘content’)
</div>
<script src=”https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js”></script>
</body>
</html>
Modify resources/views/posts/index.blade.php:
@extends(‘layouts.app’)
@section(‘content’)
<div class=”d-flex justify-content-between align-items-center mb-3″>
<h2>All Posts</h2>
<a href=”{{ route(‘posts.create’) }}” class=”btn btn-primary”>Create Post</a>
</div>
@if (session(‘success’))
<div class=”alert alert-success”>{{ session(‘success’) }}</div>
@endif
<table class=”table table-bordered”>
<thead>
<tr>
<th>Title</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
@foreach ($posts as $post)
<tr>
<td>{{ $post->title }}</td>
<td>
<a href=”{{ route(‘posts.edit’, $post->id) }}” class=”btn btn-warning”>Edit</a>
<form action=”{{ route(‘posts.destroy’, $post->id) }}” method=”POST” class=”d-inline”>
@csrf
@method(‘DELETE’)
<button type=”submit” class=”btn btn-danger”>Delete</button>
</form>
</td>
</tr>
@endforeach
</tbody>
</table>
@endsection
This will display all posts with buttons for editing and deleting.
To improve user experience, we will implement AJAX for CRUD operations.
Modify layouts/app.blade.php and add jQuery:
<script src=”https://code.jquery.com/jquery-3.6.0.min.js”></script>
Modify posts/create.blade.php:
@extends(‘layouts.app’)
@section(‘content’)
<h2>Create Post</h2>
<form id=”createPostForm”>
@csrf
<div class=”mb-3″>
<label for=”title” class=”form-label”>Title</label>
<input type=”text” id=”title” name=”title” class=”form-control”>
</div>
<button type=”submit” class=”btn btn-primary”>Submit</button>
</form>
<div id=”successMessage” class=”alert alert-success mt-3″ style=”display: none;”>Post created successfully!</div>
<script>
$(document).ready(function(){
$(‘#createPostForm’).on(‘submit’, function(event){
event.preventDefault();
$.ajax({
url: “{{ route(‘posts.store’) }}”,
method: “POST”,
data: $(this).serialize(),
success: function(response) {
$(‘#successMessage’).show();
$(‘#createPostForm’)[0].reset();
}
});
});
});
</script>
@endsection
Now, when a user submits a post, it will be saved via AJAX without reloading the page.
Once the website is complete, we need to deploy it to a server.
For Laravel hosting, consider:
php artisan migrate –force
chmod -R 775 storage bootstrap/cache
For Apache, create a virtual host:
<VirtualHost *:80>
ServerName yourdomain.com
DocumentRoot /var/www/html/yourproject/public
<Directory /var/www/html/yourproject>
AllowOverride All
Require all granted
</Directory>
ErrorLog ${APACHE_LOG_DIR}/error.log
CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>
For Nginx, use this configuration:
server {
listen 80;
server_name yourdomain.com;
root /var/www/html/yourproject/public;
index index.php index.html;
location / {
try_files $uri $uri/ /index.php?$query_string;
}
location ~ \.php$ {
include fastcgi_params;
fastcgi_pass unix:/run/php/php8.0-fpm.sock;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
}
}
sudo systemctl restart apache2 # For Apache
sudo systemctl restart nginx # For Nginx
Throughout this five-part guide, we have explored the step-by-step process of building a website using Laravel, from setup to deployment. Let’s summarize what we have achieved:
By following this guide, you now have a fully functional Laravel-based website with authentication, CRUD operations, and deployment. Laravel’s flexibility allows further enhancements like API integration, third-party services, or advanced features like real-time notifications.
Now, you can explore:
✅ Laravel API Development
✅ Admin Dashboard Implementation
✅ E-commerce or Blogging Features
Keep learning and keep building! ????