+8801306001200
 |   | 



Laravel 9 continues to be one of the most powerful and elegant PHP frameworks for developing modern web applications. Known for its simplicity, expressive syntax, and built-in tools for rapid development, Laravel provides a solid foundation for developers to create secure and scalable applications. One of the most fundamental concepts in Laravel is CRUD — short for Create, Read, Update, and Delete. These operations form the backbone of nearly every database-driven application. In this comprehensive tutorial, we’ll walk through a step-by-step Laravel 9 CRUD example for beginners, showing how to build, test, and optimize your first CRUD system from scratch.

What is CRUD in Laravel?

CRUD represents the four essential database operations: Create new records, Read existing data, Update data, and Delete records that are no longer needed. In Laravel, CRUD operations are performed through the Eloquent ORM, a powerful Active Record implementation that simplifies database interaction using expressive PHP syntax. This means you can handle data without writing raw SQL queries — Laravel does that for you under the hood.

Each CRUD operation in Laravel involves several key components:

  • Routes define the URLs that trigger CRUD actions and link them to specific controller methods.
  • Controllers contain the logic for handling requests, processing data, and returning views or JSON responses.
  • Models represent the data structure and connect to your database tables through Eloquent ORM.
  • Views are Blade templates that display the data and forms for users to interact with.

Step 1: Setting Up Laravel 9

Before starting, ensure that your environment meets the Laravel 9 system requirements. Laravel 9 requires PHP 8.0 or higher and supports various database systems such as MySQL, PostgreSQL, SQLite, and SQL Server. You’ll also need Composer, a dependency manager for PHP.

Installing Laravel 9

Run the following command in your terminal to create a new Laravel project:

composer create-project laravel/laravel laravel9-crud

Once installed, navigate into your new project directory:

cd laravel9-crud

Then start the built-in PHP development server:

php artisan serve

Your Laravel 9 application is now running at http://localhost:8000.

Step 2: Configuring the Database

Next, you’ll need to configure your database connection. Open the .env file in the project root and update the database settings to match your local environment:

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel_crud
DB_USERNAME=root
DB_PASSWORD=

Create the database using your preferred tool, such as phpMyAdmin or MySQL Workbench. Once configured, Laravel will automatically connect to it when running migrations or interacting with models.

Running Migrations

Migrations in Laravel are used to create and modify database tables. You can generate a migration for a new model using the following Artisan command:

php artisan make:model Post -m

This creates a new model named Post and a corresponding migration file. Open the migration file located in database/migrations and define the table structure:

Schema::create('posts', function (Blueprint $table) {
    $table->id();
    $table->string('title');
    $table->text('content');
    $table->timestamps();
});

Apply the migration to create the table:

php artisan migrate

Step 3: Creating the Model and Controller

The Post model will represent a single post record in the database. It connects to the posts table automatically, following Laravel’s naming conventions. The controller will handle the logic for CRUD operations.

Generating a Controller

Run the following command to create a resource controller:

php artisan make:controller PostController --resource

This creates a controller file with all the CRUD methods pre-defined, including index, create, store, show, edit, update, and destroy.

Defining Routes

Open routes/web.php and register a resource route for the Post controller:

use App\Http\Controllers\PostController;

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

This single line of code automatically sets up all the routes required for the CRUD operations.

Step 4: Building the Blade Templates

Laravel uses Blade as its templating engine. Let’s create simple views for managing posts. Inside resources/views, create a folder named posts and add the following files: index.blade.php, create.blade.php, edit.blade.php, and show.blade.php.

Creating the Index View

This view displays all posts and links to add, edit, or delete them.

@extends('layouts.app')

@section('content')
<div class="container">
  <a href="{{ route('posts.create') }}" class="btn btn-success mb-3">Add New Post</a>
  <table class="table table-bordered">
    <tr>
      <th>Title</th>
      <th>Content</th>
      <th>Actions</th>
    </tr>
    @foreach ($posts as $post)
    <tr>
      <td>{{ $post->title }}</td>
      <td>{{ Str::limit($post->content, 50) }}</td>
      <td>
        <a href="{{ route('posts.edit', $post->id) }}" class="btn btn-primary btn-sm">Edit</a>
        <form action="{{ route('posts.destroy', $post->id) }}" method="POST" style="display:inline;">
          @csrf
          @method('DELETE')
          <button class="btn btn-danger btn-sm">Delete</button>
        </form>
      </td>
    </tr>
    @endforeach
  </table>
</div>
@endsection

Step 5: Implementing Controller Logic

Now, open the PostController.php file and implement the CRUD methods:

Store Method (Create)

public function store(Request $request)
{
    $request->validate([
        'title' => 'required|max:255',
        'content' => 'required',
    ]);

    Post::create($request->all());
    return redirect()->route('posts.index')->with('success', 'Post created successfully.');
}

Update Method

public function update(Request $request, Post $post)
{
    $request->validate([
        'title' => 'required|max:255',
        'content' => 'required',
    ]);

    $post->update($request->all());
    return redirect()->route('posts.index')->with('success', 'Post updated successfully.');
}

Destroy Method

public function destroy(Post $post)
{
    $post->delete();
    return redirect()->route('posts.index')->with('success', 'Post deleted successfully.');
}

Step 6: Testing and Debugging

After setting up your CRUD system, test all routes and forms carefully. Laravel provides excellent error handling via its built-in exception system, which will display detailed messages in development mode. For production, configure error logging and validation properly to ensure smooth user experience.

Common Issues to Watch For

  • Migration errors: Ensure all table names and model relationships are correctly defined.
  • Validation errors: Double-check field names in your Blade forms match those in your validation rules.
  • CSRF token mismatches: Always include @csrf in your forms to prevent token-related errors.
  • Route mismatches: Use the php artisan route:list command to verify route names and endpoints.
  • Missing layouts: Confirm your Blade templates are extending a valid base layout file.

Conclusion

By following this Laravel 9 CRUD tutorial, you’ve built a complete, working example of how to create, read, update, and delete records efficiently using Eloquent ORM and Blade templates. You’ve learned how to set up a Laravel project, connect it to a database, define models and controllers, create views, and test your application for common issues. CRUD operations are the foundation of dynamic web development, and mastering them in Laravel provides a powerful foundation for building complex and scalable applications. With these skills, you can now move on to advanced Laravel features like authentication, API development, and real-time broadcasting to take your web projects to the next level.