Building a simple CRUD (create, read, update, delete) application with Laravel

Building a simple CRUD (create, read, update, delete) application with Laravel

CRUD (create, read, update, delete) is a common set of operations that are used to manage data in a database. In this article, we'll build a simple CRUD application with Laravel to demonstrate how to perform these operations in a Laravel application.

Prerequisites

To follow along with this tutorial, you'll need to have the following prerequisites installed on your development machine:

  • PHP A web server (such as Apache or Nginx)

  • A database management system (such as MySQL or PostgreSQL)

  • Composer

  • You'll also need to have a basic understanding of the Laravel framework and its MVC structure. If you're new to Laravel, you might want to start by reading my previous article "Getting started with Laravel".

Setting up the project

To set up the project, create a new Laravel project using the following command:

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

This will create a new Laravel project called "laravel-crud" in a new directory. Replace "laravel-crud" with the desired name for your project.

Next, set up a database for your application. You can use a database management system such as MySQL or PostgreSQL. Once you have a database set up, update the .env file in the root of your project with the correct database credentials.

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

Creating the model and migration

In Laravel, a model represents a database table. We'll start by creating a model and a migration for our application.

To create a model and a migration, run the following Artisan command:

php artisan make:model Post -m

This will create a Post model and a migration file for creating a posts table in the database.

Next, open the migration file located in database/migrations and define the columns for the posts table. The up method is used to create the table, and the down method is used to drop the table.

Here is an example of the up method:

public function up()
{

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

}

This creates a posts table with an id, title, body, and created_at and updated_at columns.

To create the posts table in the database, run the following command:

php artisan migrate

laravel crud db showing post table

app/Models/Post.php

<?php
namespace App\Models;

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

class Post extends Model
{
    use HasFactory;

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

Creating the controller and routes

Next, we'll create a controller and define the routes for our CRUD operations.

To create a controller, run the following Artisan command:

php artisan make:controller PostsController

This will create a PostsController class in the app/Http/Controllers directory.

Next, define the routes for the CRUD operations in the routes/web.php file. Here is an example of how to define the routes:

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

This defines the following routes:

GET /posts: index

GET /posts/create: create

POST /posts

Run the command below to see a list of routes

Writing the CRUD functions

Now that we have our routes and controller set up, we can write the functions for each of the CRUD operations.

  1. "index" function, we'll retrieve all the posts from the database and pass them to the posts.index view,

  2. "create" function, we'll simply render the posts.create view,

  3. "store" function, we'll create a new post using the request data and save it to the database,

  4. "show" function, we'll retrieve a single post from the database based on its ID and pass it to the posts.show view,

  5. "edit" function, we'll retrieve a single post from the database based on its ID and pass it to the posts.edit view

  6. "update" function, we'll retrieve a single post from the database based on its ID, update it with the request data, and save it to the database

  7. Finally, for the "destroy" function, we'll retrieve a single post from the database based on its ID and delete it.

visit app/Http/controllers and open the PostsController.php file then update the following code into it:

<?php

namespace App\Http\Controllers;

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

class PostsController extends Controller
{
    /**
     * This method retrieve all the posts from the database and pass them to the posts.index view
     *
     * @return void
     */
    public function index()
    {
        $posts = Post::all();
        return view('posts.index', ['posts' => $posts]);
    }

    /**
     * This method simply render the posts.create view
     *
     * @return void
     */
    public function create()
    {
        return view('posts.create');
    }

    /**
     * This method will create a new post using the request data and save it to the database
     *
     * @param Request $request
     * @return void
     */
    public function store(Request $request)
    {
        $post = Post::create([
            "title" => $request->title,
            "body" => $request->body,
        ]);
        return redirect('/posts');
    }

    /**
     * This method will retrieve a single post from the database based on its ID and pass it to the posts.show view
     *
     * @param Post $post
     * @return void
     */
    public function show(Post $post)
    {
        return view('posts.show', ['post' => $post]);
    }

    /**
     * This method will retrieve a single post from the database based on its ID and pass it to the posts.edit view
     *
     * @param Post $post
     * @return void
     */
    public function edit(Post $post)
    {
        return view('posts.edit', ['post' => $post]);
    }

    /**
     * This method will retrieve a single post from the database based on its ID, update it with the request data, and save it to the database
     *
     * @param Request $request
     * @param Post $post
     * @return void
     */
    public function update(Request $request, Post $post)
    {
        $post->update([
            "title" => $request->title,
            "body" => $request->body,
        ]);
        return redirect('/posts');
    }

    /**
     * This method will retrieve a single post from the database based on its ID and delete it
     *
     * @param Post $post
     * @return void
     */
    public function destroy(Post $post)
    {
        $post->delete();
        return redirect('/posts');
    }
}

Creating the views

Now that we have our controller and CRUD functions set up, we can create the views for each of the operations.

Create a directory named "posts" within the "resources/views" directory. Inside the "posts" directory, create the following files:

  • index.blade.php

  • create.blade.php

  • show.blade.php

  • edit.blade.php

In addition to creating the "posts" directory and the associated blade files, you should also create a layout file that will be used across all views within the resources/views directory.

Create a layout file within the "resources/views" directory and name it "app.blade.php"

And then in each of the blade files (index.blade.php, create.blade.php, show.blade.php, and edit.blade.php) use the layout file by adding the following code at the top of each blade file:

@extends('app')

This will ensure that the layout is applied to all views within the "resources/views" directory.

Make sure to update the appropriate code in each of these files.

index.blade.php:

@extends('app')

@section('content')
    <h1>Blog Posts</h1>
    <ul>
        @foreach ($posts as $post)
            <li>
              <a href="/posts/{{ $post->id }}">
                {{ $post->title }}
              </a>
            </li>
        @endforeach
    </ul>
@endsection

create.blade.php

@extends('app')
@section('content')
    <h1>Create a new post</h1>
    <form action="/posts" method="post">
        @csrf
        <div>
            <label for="title">Title:</label>
            <input type="text" name="title" id="title">
        </div>
        <div>
            <label for="body">Body:</label>
            <textarea name="body" id="body"></textarea>
        </div>
        <div>
            <button type="submit">Create</button>
        </div>
    </form>
@endsection

show.blade.php

@extends('app')
@section('content')
    <h1>{{ $post->title }}</h1>
    <p>{{ $post->body }}</p>
    <p>
      <form action="{{ route('posts.destroy',$post->id) }}" method="Post">
        <a class="btn bg-blue-700" href="{{ route('posts.edit',$post->id) }}">Edit</a>
        @csrf
        @method('DELETE')
        <button type="submit" class="btn btn-danger">Delete</button>
    </form>
    </p>
@endsection

edit.blade.php

@extends('app')
@section('content')
    <h1>Edit post</h1>

    <form action="/posts/{{ $post->id }}" method="post">
        @csrf
        @method('put')

        <div>
            <label for="title">Title:</label>
            <input type="text" name="title" id="title" value="{{ $post->title }}">
        </div>
        <div>
            <label for="body">Body:</label>
            <textarea name="body" id="body">{{ $post->body }}</textarea>
        </div>
        <div>
            <button type="submit">Update</button>
        </div>
    </form>
@endsection

Run Development Server

In the final step, open a terminal window and enter the command:

php artisan serve

This will start the development server. Once the server is running, open your web browser and navigate to the following URL:

This will open the homepage of your application and you can start testing it.

localhost:8000

Conclusion

In this tutorial, we've built a simple CRUD application with Laravel. We covered how to create a model and a migration for storing data in the database, how to create a controller and define routes for the CRUD operations, and how to write the functions for each of the operations. We also covered how to create the views for displaying the data.

CRUD operations are a fundamental part of many web applications, and Laravel makes it easy to implement them with its powerful database query builder and Eloquent ORM. With these tools, you can quickly and easily build a wide range of applications with Laravel.

I hope this article has helped you get started with building CRUD applications with Laravel. If you have any questions or feedback, please let me know in the comments below.