Laravel 12 CRUD Tutorial: Step-by-Step Guide

In this tutorial, I will walk you through building a CRUD (Create, Read, Update, Delete) application in Laravel 12. CRUD operations are essential for managing data in any web application, and Laravel makes it simple with its powerful Eloquent ORM and built-in features.

I will cover everything step by step, from setting up a Laravel project to implementing CRUD functionalities for a database table. By the end of this guide, you will have a fully functional CRUD system that you can customize for your own projects.

Laravel 12 CRUD Tutorial: Step-by-Step Guide

Laravel 12 CRUD Tutorial: Step-by-Step Guide

 

Step 1: Install Laravel 12

First, install Laravel 12 using Composer:

laravel new laravel-12-crud

 

Step 2: Configure Database

Update your env file with database credentials:

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel-12-crud-example
DB_USERNAME=root
DB_PASSWORD=

Run the migration command to create default tables:

php artisan migrate

 

Step 3: Define Migration Schema

Generate a model, migration, and controller for the Post entity:

php artisan make:model Post -mcr

This command creates:

  • A Post model
  • A migration file in database/migrations/
  • A resource controller in app/Http/Controllers/PostController.php

Open the migration file in database/migrations/ and update the schema:

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        Schema::create('posts', function (Blueprint $table) {
            $table->id();
            $table->string('title');
            $table->text('content');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::dropIfExists('posts');
    }
};

 Run the migration:

php artisan migrate

 

Step 4: Define Model

Open app/Models/Post.php and update it:

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Factories\HasFactory;

class Post extends Model
{
    use HasFactory;

    protected $fillable = ['title', 'content'];
}

 

Step 5: Define Routes

Open routes/web.php and add routes:

<?php

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\PostController;

Route::get('/', function () {
    return view('welcome');
});

Route::resource('posts', PostController::class);

 

Step 6: Implement Controller Methods

Open app/Http/Controllers/PostController.php and update the methods:

namespace App\Http\Controllers;

use App\Models\Post;
use Illuminate\Http\Request;

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',
            'content' => 'required',
        ]);

        Post::create($request->all());

        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',
            'content' => '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.');
    }
}

 

Step 7: Update AppServiceProvider

Open app/Provides/AppServiceProvider.php and update the file for bootstrap 5 pagination:

<?php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;
use Illuminate\Pagination\Paginator;

class AppServiceProvider extends ServiceProvider
{
    /**
     * Register any application services.
     */
    public function register(): void
    {
        //
    }

    /**
     * Bootstrap any application services.
     */
    public function boot(): void
    {
        Paginator::useBootstrapFive();
    }
}
 
Step 8: Create Blade Views

1. Layout File (resources/views/layouts/app.blade.php)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Laravel 12 CRUD - Techsolutionstuff</title>
    <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
    <div class="container mt-5">
        @yield('content')
    </div>
</body>
</html>

2. Index Page (resources/views/posts/index.blade.php)

@extends('layouts.app')

@section('content')
<div class="d-flex justify-content-between mb-3">
    <h2>Post List</h2>
    <a class="btn btn-primary" href="{{ route('posts.create') }}">Create Post</a>
</div>

@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>Action</th>
    </tr>
    @foreach ($posts as $post)
    <tr>
        <td>{{ $post->id }}</td>
        <td>{{ $post->title }}</td>
        <td>
            <a class="btn btn-info btn-sm" href="{{ route('posts.show', $post) }}">Show</a>
            <a class="btn btn-warning btn-sm" href="{{ route('posts.edit', $post) }}">Edit</a>
            <form action="{{ route('posts.destroy', $post) }}" method="POST" class="d-inline">
                @csrf @method('DELETE')
                <button type="submit" class="btn btn-danger btn-sm">Delete</button>
            </form>
        </td>
    </tr>
    @endforeach
</table>

{{ $posts->links() }}
@endsection

3. Create Page (resources/views/posts/create.blade.php)

@extends('layouts.app')

@section('content')
<h2>Create Post</h2>
<form action="{{ route('posts.store') }}" method="POST">
    @csrf
    <div class="mb-3">
        <label>Title</label>
        <input type="text" name="title" class="form-control" required>
    </div>
    <div class="mb-3">
        <label>Content</label>
        <textarea name="content" class="form-control" required></textarea>
    </div>
    <button type="submit" class="btn btn-primary">Submit</button>
</form>
@endsection

4. Edit Page (resources/views/posts/edit.blade.php)

@extends('layouts.app')

@section('content')
<h2>Edit Post</h2>
<form action="{{ route('posts.update', $post) }}" method="POST">
    @csrf @method('PUT')
    <div class="mb-3">
        <label>Title</label>
        <input type="text" name="title" value="{{ $post->title }}" class="form-control" required>
    </div>
    <div class="mb-3">
        <label>Content</label>
        <textarea name="content" class="form-control" required>{{ $post->content }}</textarea>
    </div>
    <button type="submit" class="btn btn-primary">Update</button>
</form>
@endsection

 

Step 9: Run the Application

Start the Laravel server:

php artisan serve

 


You might also like:

techsolutionstuff

Techsolutionstuff | The Complete Guide

I'm a software engineer and the founder of techsolutionstuff.com. Hailing from India, I craft articles, tutorials, tricks, and tips to aid developers. Explore Laravel, PHP, MySQL, jQuery, Bootstrap, Node.js, Vue.js, and AngularJS in our tech stack.

RECOMMENDED POSTS

FEATURE POSTS