Building a Simple CRUD Application in Laravel
Creating a basic CRUD (Create, Read, Update, Delete) application is one of the foundational skills in web development. In this tutorial, we’ll walk through the process of setting up a simple CRUD application using Laravel 11. By the end of this guide, you’ll have a working application that allows you to manage posts.
Step 1: Set Up Laravel
To get started, we need to install Laravel. Ensure you have Composer installed, then run the following commands to create a new Laravel project and start the development server:
composer create-project --prefer-dist laravel/laravel laravel-crud
cd laravel-crud
php artisan serve
After running the php artisan serve
command, your application should be accessible at http://localhost:8000
.
Step 2: Configure the Database
Next, configure your database connection in the .env
file located in the root directory of your Laravel project. Update the following lines with your database credentials:
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=your_database_name
DB_USERNAME=your_database_username
DB_PASSWORD=your_database_password
Step 3: Create a Model and Migration
Now, let’s create a Post
model along with its corresponding migration file:
php artisan make:model Post -m
The migration file will be located in the database/migrations
directory. Open the file and define the schema for the posts
table:
public function up()
{
Schema::create('posts', function (Blueprint $table) {
$table->id();
$table->string('title');
$table->text('content');
$table->timestamps();
});
}
Run the migration to create the table in your database:
php artisan migrate
Step 4: Create a Controller
We need a controller to handle the CRUD operations for our Post
model. Use the following command to generate a PostController
:
php artisan make:controller PostController
Now, let’s define the methods in PostController
to handle CRUD operations. Open app/Http/Controllers/PostController.php
and add the following code:
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|string|max:255',
'content' => 'required|string',
]);
Post::create($request->all());
return redirect()->route('posts.index');
}
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|string|max:255',
'content' => 'required|string',
]);
$post->update($request->all());
return redirect()->route('posts.index');
}
public function destroy(Post $post)
{
$post->delete();
return redirect()->route('posts.index');
}
}
Step 5: Define the Post Model
Ensure that your Post
model is correctly defined to handle mass assignment. Open app/Models/Post.php
and add the following code:
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
use HasFactory;
protected $fillable = ['title', 'content'];
}
Step 6: Create Blade Templates
Laravel uses Blade as its templating engine. We’ll create views for listing posts, creating a new post, editing a post, and displaying a single post.
First, create a layout template at resources/views/layouts/app.blade.php
:
<html>
<head>
<title>App Name - @yield('title')</title>
</head>
<body>
<div class="container">
@yield('content')
</div>
</body>
</html>
Then, create the necessary views under resources/views/posts
:
index.blade.php
:
@extends('layouts.app')
@section('content')
<h1>Posts</h1>
<a href="{{ route('posts.create') }}">Create New Post</a>
<ul>
@foreach ($posts as $post)
<li>
<a href="{{ route('posts.show', $post) }}">{{ $post->title }}</a>
<a href="{{ route('posts.edit', $post) }}">Edit</a>
<form action="{{ route('posts.destroy', $post) }}" method="POST" style="display:inline;">
@csrf
@method('DELETE')
<button type="submit">Delete</button>
</form>
</li>
@endforeach
</ul>
@endsection
create.blade.php
:
@extends('layouts.app')
@section('content')
<h1>Create Post</h1>
<form action="{{ route('posts.store') }}" method="POST">
@csrf
<div>
<label for="title">Title:</label>
<input
type="text"
name="title"
id="title"
class="@error('title') is-invalid @enderror"
value="{{ old('title') }}">
@error('title')
<div class="alert alert-danger">{{ $message }}</div>
@enderror
</div>
<div>
<label for="content">Content:</label>
<textarea
name="content"
id="content"
class="@error('content') is-invalid @enderror">
{{ old('content') }}
</textarea>
@error('content')
<div class="alert alert-danger">{{ $message }}</div>
@enderror
</div>
<button type="submit">Create Post</button>
</form>
@endsection
edit.blade.php
:
@extends('layouts.app')
@section('content')
<h1>Edit Post</h1>
<form action="{{ route('posts.update', $post) }}" method="POST">
@csrf
@method('PUT')
<div>
<label for="title">Title:</label>
<input
type="text"
name="title"
id="title"
value="{{ $post->title }}">
@error('title')
<div class="alert alert-danger">{{ $message }}</div>
@enderror
</div>
<div>
<label for="content">Content:</label>
<textarea
name="content"
id="content">
{{ $post->content }}
</textarea>
@error('content')
<div class="alert alert-danger">{{ $message }}</div>
@enderror
</div>
<button type="submit">Update Post</button>
</form>
@endsection
show.blade.php
:
@extends('layouts.app')
@section('content')
<h1>{{ $post->title }}</h1>
<p>{{ $post->content }}</p>
<a href="{{ route('posts.edit', $post) }}">Edit</a>
<form action="{{ route('posts.destroy', $post) }}" method="POST" style="display:inline;">
@csrf
@method('DELETE')
<button type="submit">Delete</button>
</form>
<div>
<a href="{{ route('posts.index') }}">Back to List</a>
</div>
@endsection
Step 7: Define Routes
Finally, we need to define routes for our CRUD operations. Open routes/web.php
and add the following line:
use App\Http\Controllers\PostController;
Route::resource('posts', PostController::class);
Step 8: Test the Application
To test the CRUD functionality, navigate to http://localhost:8000/posts
. You should be able to create, view, edit, and delete posts through the user interface.
Conclusion
This guide walked you through the process of building a simple CRUD application in Laravel 11. You learned how to set up a Laravel project, configure the database, create models and controllers, and build Blade templates for views. With these skills, you can create more complex applications and dive deeper into Laravel’s robust features.