CRUD Operation in Laravel: Step-by-Step Guide with Example
If you are working with Laravel, one of the most common tasks you will encounter is performing CRUD operations. CRUD stands for Create, Read, Update, and Delete — the basic operations required to manage any kind of data. In this tutorial, we will build a simple blog system with posts using Laravel’s CRUD functionality.
What is CRUD in Laravel?
CRUD allows you to interact with the database and perform data manipulation with the help of Laravel’s Eloquent ORM. Using CRUD operations, you can insert new records, fetch existing data, update records, and delete data from the database easily.
Steps to Perform CRUD in Laravel
1. Create Migration and Model
First, create a migration and model for the posts table using artisan command:
php artisan make:model Post -m
This will generate a model Post.php inside app/Models and a migration file in database/migrations.
Migration File (database/migrations/xxxx_create_posts_table.php)
public function up()
{
Schema::create('posts', function (Blueprint $table) {
$table->id();
$table->string('title');
$table->text('description');
$table->string('meta_title')->nullable();
$table->string('meta_description')->nullable();
$table->string('keywords')->nullable();
$table->string('slug')->unique();
$table->timestamps();
});
}
Model File (app/Models/Post.php)
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
use HasFactory;
protected $fillable = [
'title',
'description',
'meta_title',
'meta_description',
'keywords',
'slug',
];
}
2. Define Routes
In routes/web.php, add routes for CRUD operations:
use App\Http\Controllers\PostController;
Route::resource('posts', PostController::class);
3. Create Controller
Generate a controller using artisan:
php artisan make:controller PostController --resource
This will create a controller with all CRUD methods like index, create, store, edit, update, and destroy.
PostController.php (Complete Code)
namespace App\Http\Controllers;
use App\Models\Post;
use Illuminate\Http\Request;
use Illuminate\Support\Str;
class PostController extends Controller
{
public function index()
{
$posts = Post::latest()->paginate(5);
return view('posts.index', compact('posts'));
}
public function create()
{
return view('posts.create');
}
public function store(Request $request)
{
$request->validate([
'title' => 'required|unique:posts|max:255',
'description' => 'required',
]);
Post::create([
'title' => $request->title,
'description' => $request->description,
'meta_title' => $request->meta_title,
'meta_description' => $request->meta_description,
'keywords' => $request->keywords,
'slug' => Str::slug($request->title),
]);
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|max:255|unique:posts,title,' . $post->id,
'description' => 'required',
]);
$post->update([
'title' => $request->title,
'description' => $request->description,
'meta_title' => $request->meta_title,
'meta_description' => $request->meta_description,
'keywords' => $request->keywords,
'slug' => Str::slug($request->title),
]);
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.');
}
}
4. Create Blade Views
Now create Blade templates inside resources/views/posts for listing, adding, editing, and deleting posts.
Index View (resources/views/posts/index.blade.php)
@extends('layouts.app')
@section('content')
<div class="container">
<h1>All Posts</h1>
<a href="{{ route('posts.create') }}" class="btn btn-success mb-3">Add New Post</a>
@if(session('success'))
<div class="alert alert-success">{{ session('success') }}</div>
@endif
<table class="table table-bordered">
<tr>
<th>ID</th>
<th>Title</th>
<th>Slug</th>
<th width="200px">Action</th>
</tr>
@foreach($posts as $post)
<tr>
<td>{{ $post->id }}</td>
<td>{{ $post->title }}</td>
<td>{{ $post->slug }}</td>
<td>
<a href="{{ route('posts.show',$post->id) }}" class="btn btn-info btn-sm">Show</a>
<a href="{{ route('posts.edit',$post->id) }}" class="btn btn-warning btn-sm">Edit</a>
<form action="{{ route('posts.destroy',$post->id) }}" method="POST" style="display:inline">
@csrf @method('DELETE')
<button type="submit" class="btn btn-danger btn-sm"
onclick="return confirm('Are you sure?')">Delete</button>
</form>
</td>
</tr>
@endforeach
</table>
{{ $posts->links() }}
</div>
@endsection
Create View (resources/views/posts/create.blade.php)
@extends('layouts.app')
@section('content')
<div class="container">
<h1>Add New Post</h1>
<form action="{{ route('posts.store') }}" method="POST">
@csrf
<div class="mb-3">
<label>Title</label>
<input type="text" name="title" class="form-control">
</div>
<div class="mb-3">
<label>Description</label>
<textarea name="description" class="form-control"></textarea>
</div>
<button type="submit" class="btn btn-success">Save</button>
</form>
</div>
@endsection
Show View (resources/views/posts/show.blade.php)
@extends('layouts.app')
@section('content')
<div class="container">
<h1>{{ $post->title }}</h1>
<p>{!! $post->description !!}</p>
<a href="{{ route('posts.index') }}" class="btn btn-secondary">Back</a>
</div>
@endsection
Edit View (resources/views/posts/edit.blade.php)
@extends('layouts.app')
@section('content')
<div class="container">
<h1>Edit Post</h1>
<form action="{{ route('posts.update',$post->id) }}" method="POST">
@csrf @method('PUT')
<div class="mb-3">
<label>Title</label>
<input type="text" name="title" value="{{ $post->title }}" class="form-control">
</div>
<div class="mb-3">
<label>Description</label>
<textarea name="description" class="form-control">{{ $post->description }}</textarea>
</div>
<button type="submit" class="btn btn-primary">Update</button>
</form>
</div>
@endsection
Conclusion
With these simple steps, you can build a fully functional CRUD system in Laravel. Laravel makes CRUD operations straightforward with its powerful Eloquent ORM and Blade templating engine. Once you master CRUD in Laravel, you’ll be ready to build more complex web applications with ease.