Laravel CRUD Example Tutorial for Beginners

Laravel CRUD Example Tutorial for Beginners

Today we will be learning how to create a Laravel CRUD (Create, Read, Update, Delete) web application step by step from scratch.

 let's go through the steps to create a Laravel CRUD application with the fields name, email, and address in a fresh Laravel project. We'll create the model, migration, controller, and views.

Step 1: Create a New Laravel Project
Step 2: Create a Model, Migration, and Controller
Step 3: Define Database Schema
Step 4: Create Controller Methods
Step 5: Create Views
Step 6: Routes
Step 7: Run the Application

Step 1: Create a New Laravel Project:

Create a new Laravel project using Composer:

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

Navigate to the project directory:

cd laravel-crud

Step 2: Create a Model, Migration, and Controller:

Generate a model, migration, and controller for a resource (e.g., Contact):

php artisan make:model Contact -m -c

Step 3: Define Database Schema

Edit the generated migration file (database/migrations/xxxx_xx_xx_create_contacts_table.php) to define the database schema for the contacts table:

// database/migrations/xxxx_xx_xx_create_contacts_table.php

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

class CreateContactsTable extends Migration
{
    public function up()
    {
        Schema::create('contacts', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->string('email')->unique();
            $table->text('address');
            $table->timestamps();
        });
    }

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

Run the migration to create the table:

php artisan migrate

Step 4: Create Controller Methods:

Edit the ContactController (app/Http/Controllers/ContactController.php) to implement CRUD operations:

// app/Http/Controllers/ContactController.php

namespace App\Http\Controllers;

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

class ContactController extends Controller
{
    public function index()
    {
        $contacts = Contact::all();
        return view('contacts.index', compact('contacts'));
    }

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

    public function store(Request $request)
    {
        Contact::create($request->all());
        return redirect()->route('contacts.index')->with('success', 'Contact created successfully.');
    }

    public function show($id)
    {
        $contact = Contact::findOrFail($id);
        return view('contacts.show', compact('contact'));
    }

    public function edit($id)
    {
        $contact = Contact::findOrFail($id);
        return view('contacts.edit', compact('contact'));
    }

    public function update(Request $request, $id)
    {
        $contact = Contact::findOrFail($id);
        $contact->update($request->all());
        return redirect()->route('contacts.index')->with('success', 'Contact updated successfully.');
    }

    public function destroy($id)
    {
        $contact = Contact::findOrFail($id);
        $contact->delete();
        return redirect()->route('contacts.index')->with('success', 'Contact deleted successfully.');
    }
}

Step 5: Create Views:

Create Blade views in resources/views/contacts:

index.blade.php

<!-- resources/views/contacts/index.blade.php -->

@extends('layouts.app')

@section('content')
    <h2>Contact List</h2>
    <a href="{{ route('contacts.create') }}" class="btn btn-primary">Add Contact</a>
    <table class="table mt-3">
        <thead>
            <tr>
                <th>ID</th>
                <th>Name</th>
                <th>Email</th>
                <th>Address</th>
                <th>Actions</th>
            </tr>
        </thead>
        <tbody>
            @foreach($contacts as $contact)
                <tr>
                    <td>{{ $contact->id }}</td>
                    <td>{{ $contact->name }}</td>
                    <td>{{ $contact->email }}</td>
                    <td>{{ $contact->address }}</td>
                    <td>
                        <a href="{{ route('contacts.show', $contact->id) }}" class="btn btn-info">View</a>
                        <a href="{{ route('contacts.edit', $contact->id) }}" class="btn btn-warning">Edit</a>
                        <form action="{{ route('contacts.destroy', $contact->id) }}" method="POST" style="display:inline">
                            @csrf
                            @method('DELETE')
                            <button type="submit" class="btn btn-danger" onclick="return confirm('Are you sure?')">Delete</button>
                        </form>
                    </td>
                </tr>
            @endforeach
        </tbody>
    </table>
@endsection

create.blade.php

<!-- resources/views/contacts/create.blade.php -->

@extends('layouts.app')

@section('content')
    <h2>Create Contact</h2>
    <form action="{{ route('contacts.store') }}" method="POST">
        @csrf
        <div class="mb-3">
            <label for="name" class="form-label">Name</label>
            <input type="text" class="form-control" id="name" name="name" required>
        </div>
        <div class="mb-3">
            <label for="email" class="form-label">Email</label>
            <input type="email" class="form-control" id="email" name="email" required>
        </div>
        <div class="mb-3">
            <label for="address" class="form-label">Address</label>
            <textarea class="form-control" id="address" name="address" rows="3" required></textarea>
        </div>
        <button type="submit" class="btn btn-primary">Save</button>
    </form>
@endsection

show.blade.php

<!-- resources/views/contacts/show.blade.php -->

@extends('layouts.app')

@section('content')
    <h2>Contact Details</h2>
    <p><strong>Name:</strong> {{ $contact->name }}</p>
    <p><strong>Email:</strong> {{ $contact->email }}</p>
    <p><strong>Address:</strong> {{ $contact->address }}</p>
    <a href="{{ route('contacts.index') }}" class="btn btn-secondary">Back to List</a>
@endsection

edit.blade.php

<!-- resources/views/contacts/edit.blade.php -->

@extends('layouts.app')

@section('content')
    <h2>Edit Contact</h2>
    <form action="{{ route('contacts.update', $contact->id) }}" method="POST">
        @csrf
        @method('PUT')
        <div class="mb-3">
            <label for="name" class="form-label">Name</label>
            <input type="text" class="form-control" id="name" name="name" value="{{ $contact->name }}" required>
        </div>
        <div class="mb-3">
            <label for="email" class="form-label">Email</label>
            <input type="email" class="form-control" id="email" name="email" value="{{ $contact->email }}" required>
        </div>
        <div class="mb-3">
            <label for="address" class="form-label">Address</label>
            <textarea class="form-control" id="address" name="address" rows="3" required>{{ $contact->address }}</textarea>
        </div>
        <button type="submit" class="btn btn-primary">Update</button>
    </form>
    <a href="{{ route('contacts.index') }}" class="btn btn-secondary mt-2">Back to List</a>
@endsection

Step 6: Routes:

Add the following route definition in routes/web.php:

// routes/web.php

use App\Http\Controllers\ContactController;

Route::resource('contacts', ContactController::class);

Step 7: Run the Application

Run the development server:

php artisan serve

Visit http://localhost:8000/contacts in your browser to see the list of contacts and perform CRUD operations.

This is a basic example, and you can enhance it by adding validation, error handling, and more features based on your requirements. Additionally, you might want to use Laravel Collective or JavaScript frameworks for form handling to make the user experience smoother.




Mahendra Pratap Singh

Hey there! I'm a Senior Full Stack Developer with 10 +years of experience in the tech world. I've spent a lot of time working with different tools and languages, like PHP, WordPress, Laravel, and CodeIgniter... Read More >>

Leave a Comment