Building a Simple Web Application with Laravel
Introduction
Laravel is a popular PHP framework known for its elegant syntax and robust features. It simplifies the development process by providing tools and resources that enhance productivity and ensure code quality. In this article, we will walk through the steps of building a simple web application with Laravel, covering application design and architecture, implementing key features, and integrating with a database.
Project Structure
Here is the complete structure of the sample project:
simple_web_app/
├── app/
│ ├── Console/
│ ├── Exceptions/
│ ├── Http/
│ │ ├── Controllers/
│ │ │ ├── PostController.php
│ │ ├── Middleware/
│ ├── Models/
│ │ ├── Post.php
│ ├── Providers/
├── bootstrap/
├── config/
├── database/
│ ├── factories/
│ ├── migrations/
│ │ ├── xxxx_xx_xx_create_posts_table.php
│ ├── seeders/
├── public/
├── resources/
│ ├── views/
│ │ ├── posts/
│ │ │ ├── create.blade.php
│ │ │ ├── edit.blade.php
│ │ │ ├── index.blade.php
│ │ │ ├── show.blade.php
├── routes/
│ ├── web.php
├── storage/
├── tests/
├── .env
├── artisan
├── composer.json
└── package.json
This structure includes the necessary controllers, models, migrations, and views to implement the simple blog application described in this article. Feel free to expand and customize it to fit your needs.
Setting Up Your Environment
- Install Composer: Laravel uses Composer for dependency management. Ensure you have it installed on your machine.
- Install Laravel: Run the following command to install Laravel:
composer create-project --prefer-dist laravel/laravel simple_web_app
3.Create posgresql database named simple_web_app_db
If you are using ubuntu / linux as database server, you can follow this command line.
4. Set Up Your Development Environment: Configure your .env
file with your database credentials.
in my case is
DB_CONNECTION=pgsql
DB_HOST=127.0.0.1
DB_PORT=5432
DB_DATABASE=simple_web_app_db
DB_USERNAME=postgres
DB_PASSWORD=zuruck
5. Make your db accessible from pgadmin app
Update your pg_ba.conf
Add the following into the last line
host simple_web_app_db postgres 0.0.0.0/0 md5
restart the postgresql
Application Design and Architecture
Before diving into the code, it’s essential to plan your application’s architecture. We’ll be building a simple blog application with the following features:
- User registration and authentication
- Creating, editing, and deleting posts
- Viewing a list of posts
MVC Structure
Laravel follows the Model-View-Controller (MVC) architectural pattern, which helps in separating concerns and organizing the codebase efficiently.
Implementing Key Features
User Registration and Authentication
Laravel provides built-in authentication, making it easy to set up:
- Install Laravel UI Package:
composer require laravel/ui
2. Generate Auth Scaffolding:
Make sure your node version is above version 15 to be able to run npm run dev without error
php artisan ui vue --auth
npm install && npm run dev
php artisan migrate
This will generate the necessary routes, controllers, and views for user authentication.
Creating the Post Model and Migration
- Generate Model and Migration:
php artisan make:model Post -m
2. Define the Posts Table Schema in the migration file (database/migrations/xxxx_xx_xx_create_posts_table.php
):
public function up()
{
Schema::create('posts', function (Blueprint $table) {
$table->id();
$table->string('title');
$table->text('body');
$table->foreignId('user_id')->constrained()->onDelete('cascade');
$table->timestamps();
});
}
3. Run the Migration:
php artisan migrate
It will create post table
Creating, Editing, and Deleting Posts
- Generate Controller:
php artisan make:controller PostController --resource
2. Define Routes in routes/web.php
:
Route::resource('posts', PostController::class);
3. Implement CRUD Operations in app/Http/Controllers/PostController.php
:
namespace App\Http\Controllers;
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',
'body' => 'required',
]);
$post = new Post;
$post->title = $request->title;
$post->body = $request->body;
$post->user_id = auth()->id();
$post->save();
return redirect()->route('posts.index')->with('success', 'Post created successfully.');
}
public function show(Post $post)
{
return view('posts.show', compact('post'));
}
public function edit(Post $post)
{
return view('posts.edit', compact('post'));
}
public function update(Request $request, Post $post)
{
$request->validate([
'title' => 'required',
'body' => 'required',
]);
$post->update($request->all());
return redirect()->route('posts.index')->with('success', 'Post updated successfully.');
}
public function destroy(Post $post)
{
$post->delete();
return redirect()->route('posts.index')->with('success', 'Post deleted successfully.');
}
}
Database Integration
Laravel makes database interactions straightforward with Eloquent ORM. We’ve already set up the database migration and integrated it with our application. Here, we’ll demonstrate how to retrieve and display data using Eloquent.
- Display Posts in
resources/views/posts/index.blade.php
:
<!DOCTYPE html>
<html>
<head>
<title>Blog Posts</title>
</head>
<body>
<h1>Blog Posts</h1>
@if (session('success'))
<div>{{ session('success') }}</div>
@endif
<a href="{{ route('posts.create') }}">Create New Post</a>
<ul>
@foreach ($posts as $post)
<li>
<a href="{{ route('posts.show', $post->id) }}">{{ $post->title }}</a>
<a href="{{ route('posts.edit', $post->id) }}">Edit</a>
<form action="{{ route('posts.destroy', $post->id) }}" method="POST" style="display:inline;">
@csrf
@method('DELETE')
<button type="submit">Delete</button>
</form>
</li>
@endforeach
</ul>
</body>
</html>
2. Create Post Form in resources/views/posts/create.blade.php
:
<!DOCTYPE html>
<html>
<head>
<title>Create Post</title>
</head>
<body>
<h1>Create Post</h1>
<form action="{{ route('posts.store') }}" method="POST">
@csrf
<label for="title">Title:</label>
<input type="text" id="title" name="title">
<label for="body">Body:</label>
<textarea id="body" name="body"></textarea>
<button type="submit">Create</button>
</form>
</body>
</html>
3. Edit Post Form in resources/views/posts/edit.blade.php
:
<!DOCTYPE html>
<html>
<head>
<title>Edit Post</title>
</head>
<body>
<h1>Edit Post</h1>
<form action="{{ route('posts.update', $post->id) }}" method="POST">
@csrf
@method('PUT')
<label for="title">Title:</label>
<input type="text" id="title" name="title" value="{{ $post->title }}">
<label for="body">Body:</label>
<textarea id="body" name="body">{{ $post->body }}</textarea>
<button type="submit">Update</button>
</form>
</body>
</html>
4. View Post in resources/views/posts/show.blade.php
:
<!DOCTYPE html>
<html>
<head>
<title>{{ $post->title }}</title>
</head>
<body>
<h1>{{ $post->title }}</h1>
<p>{{ $post->body }}</p>
<a href="{{ route('posts.index') }}">Back to Posts</a>
</body>
</html>
Test it
To run it :
php artisan serve
visit your web using browser:
In this article, we covered the basics of building a simple web application with Laravel. We discussed application design and architecture, implemented key features such as user authentication and CRUD operations for posts, and integrated with a database using Laravel’s Eloquent ORM. This should give you a solid foundation to build more complex applications using Laravel.