Share this:

Hello dev, Today we are going to learn Building a Laravel 10 CRUD Application: A Comprehensive Tutorial. Laravel is a powerful and popular PHP framework that provides a robust and elegant solution for developing web applications.

In this tutorial, we will explore how to build a CRUD (Create, Read, Update, Delete) application using Laravel 10.

We will cover all the necessary steps, from setting up the project to implementing the CRUD functionality.

Also Read: Building a Laravel 10 Application with Vue 3: Complete Guide to CRUD Operations

Prerequisites:

Before proceeding, make sure you have the following requirements:

  • PHP installed on your system (version 8.0 or higher recommended)
  • Composer installed (the PHP dependency manager)
  • Basic understanding of PHP and web development concepts
  • Familiarity with Laravel (previous versions)

Step 1: Setting up the Laravel Project

To begin, open your terminal or command prompt and navigate to the directory where you want to create your Laravel project. Run the following command:

composer create-project --prefer-dist laravel/laravel blog

This command will create a new Laravel project named “blog.” Wait for the installation process to complete.

Step 2: Database Configuration

Next, navigate to the project’s root directory and open the .env file. Update the database configuration parameters to match your environment. For example:

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=your_database_name
DB_USERNAME=your_username
DB_PASSWORD=your_password

Save the changes and close the file.

Step 3: Creating the Database Table

In this tutorial, we will create a simple “posts” table to demonstrate the CRUD operations. Open your terminal or command prompt and run the following command:

php artisan make:migration create_posts_table --create=posts

This command will generate a new migration file. Open the created migration file (located in the database/migrations directory) and define the table structure. Here’s an example of what it might look like:

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

class CreatePostsTable extends Migration
{
    public function up()
    {
        Schema::create('posts', function (Blueprint $table) {
            $table->id();
            $table->string('title');
            $table->text('content');
            $table->timestamps();
        });
    }

    public function down()
    {
        Schema::dropIfExists('posts');
    }
}

Save the file and return to your terminal. Run the following command to execute the migration:

php artisan migrate

Also Read: Laravel 10 CRUD with Image Upload Tutorial

Step 4: Creating the Model

Laravel provides an elegant ORM (Object-Relational Mapping) called Eloquent. Let’s create a model for our “posts” table. Run the following command:

php artisan make:model Post

This command will generate a new Post.php file in the app directory. Open the file and define the table name and any additional relationships or attributes you may need. Here’s an example:

use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
    protected $fillable = ['title', 'content'];
}

Save the file.

Step 5: Creating Routes

Now, let’s define the routes for our CRUD operations. Open the routes/web.php file and add the following code:

use App\Http\Controllers\PostController;

Route::get('/posts', [PostController::class, 'index'])->name('posts.index');
Route::get('/posts/create', [PostController::class, 'create'])->name('posts.create');
Route::post('/posts', [PostController::class, 'store'])->name('posts.store');
Route::get('/posts/{post}', [PostController::class, 'show'])->name('posts.show');
Route::get('/posts/{post}/edit', [PostController::class, 'edit'])->name('posts.edit');
Route::put('/posts/{post}', [PostController::class, 'update'])->name('posts.update');
Route::delete('/posts/{post}', [PostController::class, 'destroy'])->name('posts.destroy');

Save the file.

Step 6: Creating the Controller

Now, let’s create the controller that will handle our CRUD operations. Run the following command:

php artisan make:controller PostController --resource

This command will generate a new PostController.php file in the app/Http/Controllers directory. Open the file and replace the existing code with the following:

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

class PostController extends Controller
{
    public function index()
    {
        $posts = Post::latest()->paginate(10);

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

Save the file.

Also Read: Laravel 9 JetStream Livewire CRUD Operations Tutorial

Step 7: Creating Views

Finally, let’s create the necessary views for our CRUD operations. Create the following files in the resources/views/posts directory:

  • index.blade.php (display all posts)
  • create.blade.php (create a new post)
  • show.blade.php (display a single post)
  • edit.blade.php (edit a post)

Let’s create the required views in the resources/views/posts directory:

Create index.blade.php:

This view will display all the posts in a tabular format. Open the index.blade.php file and add the following code:

<!-- resources/views/posts/index.blade.php -->
<h1>All Posts</h1>

@if (session('success'))
    <div class="alert alert-success">
        {{ session('success') }}
    </div>
@endif

<table class="table">
    <thead>
        <tr>
            <th>Title</th>
            <th>Content</th>
            <th>Actions</th>
        </tr>
    </thead>
    <tbody>
        @foreach ($posts as $post)
            <tr>
                <td>{{ $post->title }}</td>
                <td>{{ $post->content }}</td>
                <td>
                    <a href="{{ route('posts.show', $post) }}" class="btn btn-primary">View</a>
                    <a href="{{ route('posts.edit', $post) }}" class="btn btn-secondary">Edit</a>
                    <form action="{{ route('posts.destroy', $post) }}" method="POST" style="display: inline-block">
                        @csrf
                        @method('DELETE')
                        <button type="submit" class="btn btn-danger" onclick="return confirm('Are you sure?')">Delete</button>
                    </form>
                </td>
            </tr>
        @endforeach
    </tbody>
</table>

{{ $posts->links() }}

Create create.blade.php:

This view will display a form for creating a new post. Open the create.blade.php file and add the following code:

<!-- resources/views/posts/create.blade.php -->
<h1>Create Post</h1>

@if ($errors->any())
    <div class="alert alert-danger">
        <ul>
            @foreach ($errors->all() as $error)
                <li>{{ $error }}</li>
            @endforeach
        </ul>
    </div>
@endif

<form action="{{ route('posts.store') }}" method="POST">
    @csrf

    <div class="form-group">
        <label for="title">Title</label>
        <input type="text" name="title" id="title" class="form-control" required>
    </div>

    <div class="form-group">
        <label for="content">Content</label>
        <textarea name="content" id="content" class="form-control" rows="4" required></textarea>
    </div>

    <button type="submit" class="btn btn-primary">Create</button>
</form>

Create show.blade.php:

This view will display the details of a single post. Open the show.blade.php file and add the following code:

<!-- resources/views/posts/show.blade.php -->
<h1>{{ $post->title }}</h1>

<p>{{ $post->content }}</p>

<a href="{{ route('posts.edit', $post) }}" class="btn btn-secondary">Edit</a>
<form action="{{ route('posts.destroy', $post) }}" method="POST" style="display: inline-block">
    @csrf
    @method('DELETE')
    <button type="submit" class="btn btn-danger" onclick="return confirm('Are you sure?')">Delete</button>
</form>

<a href="{{ route('posts.index') }}" class="btn btn-primary">Back to all posts</a>

Create edit.blade.php:

This view will display a form for editing an existing post. Open the edit.blade.php file and add the following code:

<!-- resources/views/posts/edit.blade.php -->
<h1>Edit Post</h1>

@if ($errors->any())
    <div class="alert alert-danger">
        <ul>
            @foreach ($errors->all() as $error)
                <li>{{ $error }}</li>
            @endforeach
        </ul>
    </div>
@endif

<form action="{{ route('posts.update', $post) }}" method="POST">
    @csrf
    @method('PUT')

    <div class="form-group">
        <label for="title">Title</label>
        <input type="text" name="title" id="title" class="form-control" value="{{ $post->title }}" required>
    </div>

    <div class="form-group">
        <label for="content">Content</label>
        <textarea name="content" id="content" class="form-control" rows="4" required>{{ $post->content }}</textarea>
    </div>

    <button type="submit" class="btn btn-primary">Update</button>
</form>

Make sure to save all the view files with their respective names in the resources/views/posts directory.

Step 8: Testing the Application

At this point, we have completed all the necessary code for our Laravel 10 CRUD application. Run the following command to start the development server:

php artisan serve

Open your web browser and access http://localhost:8000/posts. You should now be able to perform CRUD operations on the posts.

Also Read: Laravel 9 Vue JS CRUD App using Vite Example

Conclusion:

In this tutorial, we have covered the step-by-step process of building a CRUD application using Laravel 10.

We started by setting up the project, configuring the database, and creating the necessary table. We then created the model, defined routes, and implemented the CRUD operations in the controller.

Finally, we created the views to display and interact with the data. Laravel’s intuitive syntax and powerful features make it a fantastic choice for building web applications with ease.

Now that you have a solid understanding of Laravel’s CRUD functionality, you can explore further and enhance your application based on your specific requirements. Happy coding!

Share this:

Categorized in: