Upgrade & Secure Your Future with DevOps, SRE, DevSecOps, MLOps!

We spend hours on Instagram and YouTube and waste money on coffee and fast food, but won’t spend 30 minutes a day learning skills to boost our careers.
Master in DevOps, SRE, DevSecOps & MLOps!

Learn from Guru Rajesh Kumar and double your salary in just one year.



Get Started Now!

How to Perform CRUD Operations with Laravel

CRUD operations are fundamental to web applications. Here’s a step-by-step guide to setting up and performing CRUD operations in a Laravel application.

Step 1: Setting Up Laravel

  1. Install Laravel:
    Use Composer to create a new Laravel project. Open your terminal and run:
   composer create-project --prefer-dist laravel/laravel crud-example
  1. Configure the Database:
    Update your .env file with your database details:
   DB_CONNECTION=mysql
   DB_HOST=127.0.0.1
   DB_PORT=3306
   DB_DATABASE=your_database
   DB_USERNAME=your_username
   DB_PASSWORD=your_password
  1. Run Migrations:
    Execute the migrations to create the necessary database tables:
   php artisan migrate

Step 2: Creating a Model and Migration

  1. Generate a Model and Migration:
   php artisan make:model Item -m

This command creates an Item model and a migration file.

  1. Define the Database Schema:
    Open the generated migration file in database/migrations/ and define your table schema:
   public function up()
   {
       Schema::create('items', function (Blueprint $table) {
           $table->id();
           $table->string('name');
           $table->text('description')->nullable();
           $table->timestamps();
       });
   }
  1. Run the Migration:
   php artisan migrate

Step 3: Setting Up Routes

Open routes/web.php and add the routes for CRUD operations:

use App\Http\Controllers\ItemController;

Route::resource('items', ItemController::class);

Step 4: Creating a Controller

Generate a resource controller to handle CRUD operations:

php artisan make:controller ItemController --resource

Step 5: Implementing CRUD Methods in the Controller

Open app/Http/Controllers/ItemController.php and implement the CRUD methods:

namespace App\Http\Controllers;

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

class ItemController extends Controller
{
    public function index()
    {
        $items = Item::all();
        return view('items.index', compact('items'));
    }

    public function create()
    {
        return view('items.create');
    }

    public function store(Request $request)
    {
        $request->validate([
            'name' => 'required',
            'description' => 'nullable',
        ]);

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

    public function show(Item $item)
    {
        return view('items.show', compact('item'));
    }

    public function edit(Item $item)
    {
        return view('items.edit', compact('item'));
    }

    public function update(Request $request, Item $item)
    {
        $request->validate([
            'name' => 'required',
            'description' => 'nullable',
        ]);

        $item->update($request->all());
        return redirect()->route('items.index')->with('success', 'Item updated successfully.');
    }

    public function destroy(Item $item)
    {
        $item->delete();
        return redirect()->route('items.index')->with('success', 'Item deleted successfully.');
    }
}

Step 6: Creating Views

Create Blade template files for each method inside resources/views/items/:

  1. Index (index.blade.php):
   <!DOCTYPE html>
   <html>
   <head>
       <title>Items List</title>
   </head>
   <body>
       <h1>Items List</h1>
       <a href="{{ route('items.create') }}">Create New Item</a>
       <ul>
           @foreach ($items as $item)
               <li>
                   <a href="{{ route('items.show', $item->id) }}">{{ $item->name }}</a>
                   <a href="{{ route('items.edit', $item->id) }}">Edit</a>
                   <form action="{{ route('items.destroy', $item->id) }}" method="POST">
                       @csrf
                       @method('DELETE')
                       <button type="submit">Delete</button>
                   </form>
               </li>
           @endforeach
       </ul>
   </body>
   </html>
  1. Create (create.blade.php):
   <!DOCTYPE html>
   <html>
   <head>
       <title>Create Item</title>
   </head>
   <body>
       <h1>Create Item</h1>
       <form action="{{ route('items.store') }}" method="POST">
           @csrf
           <label for="name">Name:</label>
           <input type="text" name="name" id="name" required>
           <label for="description">Description:</label>
           <textarea name="description" id="description"></textarea>
           <button type="submit">Save</button>
       </form>
   </body>
   </html>
  1. Show (show.blade.php):
   <!DOCTYPE html>
   <html>
   <head>
       <title>Item Details</title>
   </head>
   <body>
       <h1>{{ $item->name }}</h1>
       <p>{{ $item->description }}</p>
       <a href="{{ route('items.index') }}">Back to List</a>
   </body>
   </html>
  1. Edit (edit.blade.php):
   <!DOCTYPE html>
   <html>
   <head>
       <title>Edit Item</title>
   </head>
   <body>
       <h1>Edit Item</h1>
       <form action="{{ route('items.update', $item->id) }}" method="POST">
           @csrf
           @method('PUT')
           <label for="name">Name:</label>
           <input type="text" name="name" id="name" value="{{ $item->name }}" required>
           <label for="description">Description:</label>
           <textarea name="description" id="description">{{ $item->description }}</textarea>
           <button type="submit">Update</button>
       </form>
   </body>
   </html>

Final Steps

  1. Start the Development Server:
   php artisan serve
  1. Access Your Application:
    Open your browser and navigate to http://localhost:8000/items to start using your CRUD application.

With these steps, you have set up a basic CRUD application using Laravel. Customize and enhance it further according to your requirements.

Related Posts

How to Disable SSL Verification in Guzzle in Laravel

When working with Guzzle, a popular PHP HTTP client, you may encounter SSL certificate issues, especially in local development environments or when connecting to servers with self-signed…

Error: Resolving the “net::ERR_INCOMPLETE_CHUNKED_ENCODING 200 (OK)” Error

1. Reload the Page Sometimes, temporary network glitches can cause this error. Simply reloading the page (Ctrl + R on Windows or Cmd + R on macOS)…

Troubleshooting Base table or view not found: 1146 Table ‘example.sessions’ doesn’t exist Error in Laravel

The error message SQLSTATE[42S02]: Base table or view not found: 1146 indicates that Laravel is trying to access a database table called sessions that doesn’t seem to…

Laravel SMTP Mailer TransportException: Connection Timeout Error

While working on a project that involved sending emails through Amazon SES (Simple Email Service) using Symfony, I encountered a frustrating error. It looked something like this:…

The Ultimate Guide to Laravel’s Folder & File Structure for Developers

Laravel Folder & File Structure Tutorial Laravel is a powerful PHP framework known for its elegant syntax and developer-friendly features. Understanding its folder and file structure is…

MVC (Model-View-Controller) in Laravel A Comprehensive Tutorial

Introduction MVC (Model-View-Controller) is a software architectural pattern that separates an application into three main logical components: Model, View, and Controller. This separation helps in organizing code,…

0 0 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x