Basic CRUD in Laravel v9

Share

This post will walk you through creating a straightforward CRUD operation app in Laravel 9. Additionally, how to validate new and updated form data on the server in a Laravel 9 CRUD app.

The abbreviation CRUD, which stands for Create, Read, Update, and Delete, is used in computer programming to refer to the four operations that are thought to be required to develop a persistent storage application.

This article’s step-by-step format covers the implementation of a straightforward Online Library CRUD operation app in a laravel 9 app with validation. Using this CRUD app, you may learn how to insert, read, update, and delete data from databases in Laravel 9.

This CRUD application contains 3 major components:

  1. Library Books
  2. Users
  3. Book Lending Details

In this article, we’ll cover the first component i.e, Library books. So let’s walk through the steps that we would follow.

Laravel 9 application scaffolding.

Download or install the latest Laravel 9 setup first. So, to install the new Laravel 9 app on your computer, open the terminal and run the following command.

** composer should be installed if not already installed on your machine

composer create-project laravel/laravel library-crud

This will create a default laravel application structure where we can write our logic. now change your terminal directory into the newly created folder i.e. library-crud: cd library-crud

Laravel folder strucutre

Connect the database

For database connection. you have to create a database using a MySQL server( PHPMyAdmin if you are using XAMPP). Create a database and note the database name. Next, find the .env file in the project folder, if not present you can generate one by using the following command:

cp .env.example .env

Next, change the value in the .env file according to your database configuration.

.env configuration

Create Model

Open again your command prompt. And run the following command on it. To create a model for Book.

php artisan make:model Book

This command creates a model file in app/Models/Book.php. Next, you have to configure some properties like fillable columns and relationships. for now, we will just configure fillable columns. To do so, you have to declare a protected $fillable property:

protected $fillable = ['title','author', 'no_of_pages','publish_date'];

So the update model file looks like this:

// Models/Book.php

<?php

namespace App\Models;

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

class Book extends Model
{
    use HasFactory;
    protected $fillable = ['title', 'author', 'no_of_pages', 'publish_date'];
}

Create Migration

Migrations files are responsible for defining the schema for an entity. To create a migration file, enter the following command:

php artisan make:migration create_books_table

This command creates a migration file in database/migrations directory. Next, we have to modify it according to the Book schema.

// database/migrations/2022_07_19_094700_create_books_table.php

<?php

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

return new class extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('books', function (Blueprint $table) {
            $table->id();
            $table->string('title');
            $table->string('author');
            $table->integer('no_of_pages');
            $table->date('publish_date');
            $table->timestamps();
        });
    }

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

After updating the column information. it’s time for deploying the table into the MySQL database. For that enter the following command in the terminal.

php artisan migrate

Create view files

View files are basically a frontend part. for the book CRUD, we will create the following 3 files in resources/views/book folder:

  1. index.blade.php – to list all books
  2. create.blade.php – form to insert a new book
  3. edit.blade.php – form to edit book details

Controller

To create a controller, run the following command in the terminal.

php artisan make:controller BookController

This command creates BookController.php file in app/http/Controllers folder.

Run development Server

To run the development server. run php artisan serve command in the terminal. it starts a server on port 8000.

Open your browser and go to: 127.0.0.1:8000, the default laravel page will appear.

Laravel default homepage

Now, we are ready to set CRUD routes.

Set Routes

To set CRUD routes open routes/web.php and paste the following code:

// routes/web.php

<?php

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

Route::resource('book', BookController::class);

After updating routes, go to 127.0.0.1:8000/book

CRUD Methods and Frontend

Now, we write methods in the controller for performing different actions. in BookController.php paste the following code.

<?php

namespace App\Http\Controllers;

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

class BookController extends Controller
{
    //
    public function index()
    {
        $books = Book::all();
        return view('books.index', compact('books'));
    }
    public function create()
    {
        return view('books.create');
    }
    public function store(Request $request)
    {
        // validate the data
        $this->validate($request, [
            'title' => 'required|max:255',
            'author' => 'required|max:255',
            'no_of_pages' => 'required|numeric',
            'publish_date' => 'required|date',
        ]);
        $book = new Book();
        $book->title = $request->title;
        $book->author = $request->author;
        $book->no_of_pages = $request->no_of_pages;
        $book->publish_date = $request->publish_date;
        $book->save();
        return redirect()->route('book.index')->with('success', 'Book created successfully');
    }
    public function show(Book $book)
    {
        return view('books.show', compact('book'));
    }
    public function edit(Book $book)
    {
        return view('books.edit', compact('book'));
    }
    public function update(Request $request, Book $book)
    {
        // validate the data
        $this->validate($request, [
            'title' => 'required|max:255',
            'author' => 'required|max:255',
            'no_of_pages' => 'required|numeric',
            'publish_date' => 'required|date',
        ]);
        $book->title = $request->title;
        $book->author = $request->author;
        $book->no_of_pages = $request->no_of_pages;
        $book->publish_date = $request->publish_date;
        $book->save();
        return redirect()->route('book.index')->with('success', 'Book updated successfully');
    }
    public function destroy(Book $book)
    {
        $book->delete();
        return redirect()->route('book.index')->with('success', 'Book deleted successfully');
    }

}

Now update the views file:

index.blade.php
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Laravel 9 CRUD From Scratch</title>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
</head>

<body>
    <div class="container mt-2">
        <div class="row">
            <div class="col-lg-12 margin-tb">
                <div class="pull-left">
                    <h2>Laravel 9 CRUD</h2>
                </div>
                <div class="pull-right mb-2">
                    <a class="btn btn-success" href="{{ route('book.create') }}"> Add Book</a>
                </div>
            </div>
        </div>
        @if ($message = Session::get('success'))
            <div class="alert alert-success">
                <p>{{ $message }}</p>
            </div>
        @endif
        <table class="table table-bordered">
            <tr>
                <th>S.No</th>
                <th>Book Title</th>
                <th>Book Author</th>
                <th>No of Pages</th>
                <th>Published Date</th>
                <th width="280px">Action</th>
            </tr>
            @php $i=0; @endphp
            @foreach ($books as $book)
            <tr>
                <td>{{ ++$i }}</td>
                <td>{{ $book->title }}</td>
                <td>{{ $book->author }}</td>
                <td>{{ $book->no_of_pages }}</td>
                <td>{{ $book->publish_date }}</td>
                <td>
                    <form action="{{ route('book.destroy',$book->id) }}" method="POST">
                        <a class="btn btn-primary" href="{{ route('book.edit',$book->id) }}">Edit</a>
                        @csrf
                        @method('DELETE')
                        <button type="submit" class="btn btn-danger">Delete</button>
                    </form>
                </td>
            @endforeach
        </table>
        {!! $books->links() !!}
</body>

</html>
create.blade.php
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>Add Book</title>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
</head>

<body>
    <div class="container mt-2">
        <div class="row">
            <div class="col-lg-12 margin-tb">
                <div class="pull-left mb-2">
                    <h2>Add Book</h2>
                </div>
                <div class="pull-right">
                    <a class="btn btn-primary" href="{{ route('book.index') }}"> Back</a>
                </div>
            </div>
        </div>
        @if (session('status'))
            <div class="alert alert-success mb-1 mt-1">
                {{ session('status') }}
            </div>
        @endif
        <form action="{{ route('book.store') }}" method="POST" enctype="multipart/form-data">
            @csrf
            <div class="row">
                <div class="col-xs-12 col-sm-12 col-md-12">
                    <div class="form-group">
                        <strong>Book Title:</strong>
                        <input type="text" name="title" class="form-control" placeholder="Book Title">
                        @error('title')
                            <div class="alert alert-danger mt-1 mb-1">{{ $message }}</div>
                        @enderror
                    </div>
                </div>
                <div class="col-xs-12 col-sm-12 col-md-12">
                    <div class="form-group">
                        <strong>Book Author:</strong>
                        <input type="text" name="author" class="form-control" placeholder="Book Author">
                        @error('author')
                            <div class="alert alert-danger mt-1 mb-1">{{ $message }}</div>
                        @enderror
                    </div>
                </div>
                <div class="col-xs-12 col-sm-12 col-md-12">
                    <div class="form-group">
                        <strong>Book Address:</strong>
                        <input type="number" name="no_of_pages" class="form-control" placeholder="No of pages">
                        @error('no_of_pages')
                            <div class="alert alert-danger mt-1 mb-1">{{ $message }}</div>
                        @enderror
                    </div>
                </div>
                <div class="col-xs-12 col-sm-12 col-md-12">
                    <div class="form-group">
                        <strong>Published Date:</strong>
                        <input type="date" name="publish_date" class="form-control" placeholder="Published Date">
                        @error('publish_date')
                            <div class="alert alert-danger mt-1 mb-1">{{ $message }}</div>
                        @enderror
                </div>
                <button type="submit" class="btn btn-primary ml-3">Submit</button>
            </div>
        </form>
</body>

</html>
edit.blade.php
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>Edit Book</title>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
</head>

<body>
    <div class="container mt-2">
        <div class="row">
            <div class="col-lg-12 margin-tb">
                <div class="pull-left mb-2">
                    <h2>Edit Book</h2>
                </div>
                <div class="pull-right">
                    <a class="btn btn-primary" href="{{ route('book.index') }}"> Back</a>
                </div>
            </div>
        </div>
        @if (session('status'))
            <div class="alert alert-success mb-1 mt-1">
                {{ session('status') }}
            </div>
        @endif
        <form action="{{ route('book.update',$book->id) }}" method="POST" enctype="multipart/form-data">
            @csrf
            @method('PUT')
            <div class="row">
                <div class="col-xs-12 col-sm-12 col-md-12">
                    <div class="form-group">
                        <strong>Book Title:</strong>
                        <input type="text" name="title" class="form-control" placeholder="Book Title" value="{{ $book->title }}">
                        @error('title')
                            <div class="alert alert-danger mt-1 mb-1">{{ $message }}</div>
                        @enderror
                    </div>
                </div>
                <div class="col-xs-12 col-sm-12 col-md-12">
                    <div class="form-group">
                        <strong>Book Author:</strong>
                        <input type="text" name="author" class="form-control" placeholder="Book Author" value="{{ $book->author }}">
                        @error('author')
                            <div class="alert alert-danger mt-1 mb-1">{{ $message }}</div>
                        @enderror
                    </div>
                </div>
                <div class="col-xs-12 col-sm-12 col-md-12">
                    <div class="form-group">
                        <strong>Book Address:</strong>
                        <input type="number" name="no_of_pages" class="form-control" placeholder="No of pages" value="{{ $book->no_of_pages }}">
                        @error('no_of_pages')
                            <div class="alert alert-danger mt-1 mb-1">{{ $message }}</div>
                        @enderror
                    </div>
                </div>
                <div class="col-xs-12 col-sm-12 col-md-12">
                    <div class="form-group">
                        <strong>Published Date:</strong>
                        <input type="date" name="publish_date" class="form-control" placeholder="Published Date" value="{{ $book->publish_date }}">
                        @error('publish_date')
                            <div class="alert alert-danger mt-1 mb-1">{{ $message }}</div>
                        @enderror
                </div>
                <button type="submit" class="btn btn-primary ml-3">Submit</button>
            </div>
        </form>
</body>
</html>

Conclusion

Form Validation
Book homepage
Edit form

Part 2: User Registration & Authentication

Laravel Official Documentation: https://laravel.com/docs/9.x

Share
Sudeep Mishra

Sudeep Mishra

Healing

%d bloggers like this: