DEV Community

Cover image for Build a clinic appointment page in Laravel, step by step
Mehedi Mansur Rafi
Mehedi Mansur Rafi

Posted on

Build a clinic appointment page in Laravel, step by step

Part 1 of Build the Clinic.

A small clinic does not need a large hospital system on day one. It needs a page where a patient can pick a doctor, choose a time, and leave a phone number, plus a simple list where staff can see who is coming tomorrow. I built that flow in Laravel for a demo clinic project, and this tutorial rebuilds it step by step. You will create the doctor and appointment tables, add a booking form with basic validation, and build an admin list with search by date. The code stays small on purpose. Nothing in the build needs a paid package, so you can follow it on a local setup. By the end you will have a working appointment page you can run locally, test with fake bookings, and change for a dental practice, a diagnostic centre, or a single doctor chamber without rewriting the whole thing.

The build has 5 parts: two tables, one form, one confirmation page, and one staff list.

Step 1: the doctors and appointments tables

Every booking points at one doctor and one time slot, so the database needs two tables.

php artisan make:model Doctor -m
php artisan make:model Appointment -m
Enter fullscreen mode Exit fullscreen mode

Doctors table:

Schema::create('doctors', function (Blueprint $table) {
    $table->id();
    $table->string('name');
    $table->string('specialty');
    $table->string('room')->nullable();
    $table->boolean('is_active')->default(true);
    $table->timestamps();
});
Enter fullscreen mode Exit fullscreen mode

Appointments table:

Schema::create('appointments', function (Blueprint $table) {
    $table->id();
    $table->foreignId('doctor_id')->constrained()->cascadeOnDelete();
    $table->string('patient_name');
    $table->string('patient_phone', 20);
    $table->date('appointment_date');
    $table->time('starts_at');
    $table->string('reason')->nullable();
    $table->string('reference', 12)->unique();
    $table->string('status', 20)->default('booked');
    $table->timestamps();

    $table->unique(['doctor_id', 'appointment_date', 'starts_at']);
});
Enter fullscreen mode Exit fullscreen mode

The last line matters. One doctor cannot hold two bookings at the same date and time. The form checks this rule in a friendly way in step 3, and this index is the hard stop behind it.

The models:

// Doctor model
protected $fillable = ['name', 'specialty', 'room', 'is_active'];

public function appointments()
{
    return $this->hasMany(Appointment::class);
}

// Appointment model
protected $fillable = [
    'doctor_id', 'patient_name', 'patient_phone',
    'appointment_date', 'starts_at', 'reason', 'reference', 'status',
];

protected $casts = ['appointment_date' => 'date'];

public function doctor()
{
    return $this->belongsTo(Doctor::class);
}
Enter fullscreen mode Exit fullscreen mode

Run the migrations, then add two test doctors:

php artisan migrate
php artisan tinker
Enter fullscreen mode Exit fullscreen mode
Doctor::create(['name' => 'Dr. Ayesha Karim', 'specialty' => 'Medicine', 'room' => '204']);
Doctor::create(['name' => 'Dr. Tanvir Hasan', 'specialty' => 'Cardiology', 'room' => '310']);
Enter fullscreen mode Exit fullscreen mode

Step 2: routes and the booking form

// routes/web.php
Route::get('/book', [AppointmentController::class, 'create'])->name('appointments.create');
Route::post('/book', [AppointmentController::class, 'store'])->name('appointments.store');
Route::get('/booking/{reference}', [AppointmentController::class, 'confirmation'])->name('appointments.confirmation');
Route::get('/staff/appointments', [StaffAppointmentController::class, 'index'])->name('staff.appointments');
Enter fullscreen mode Exit fullscreen mode

The controller holds the clinic hours as one slot list, used by the form and by validation:

class AppointmentController extends Controller
{
    private const SLOTS = [
        '09:00', '09:30', '10:00', '10:30', '11:00', '11:30',
        '14:00', '14:30', '15:00', '15:30',
    ];

    public function create()
    {
        $doctors = Doctor::where('is_active', true)->orderBy('name')->get();

        return view('appointments.create', [
            'doctors' => $doctors,
            'slots' => self::SLOTS,
        ]);
    }
}
Enter fullscreen mode Exit fullscreen mode

The form, in resources/views/appointments/create.blade.php. The date field carries a min attribute set to today. The server checks the same rule in step 3, because a browser setting can be bypassed:

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

    <label>Doctor</label>
    <select name="doctor_id" required>
        <option value="">Choose a doctor</option>
        @foreach ($doctors as $doctor)
            <option value="{{ $doctor->id }}" @selected(old('doctor_id') == $doctor->id)>
                {{ $doctor->name }} - {{ $doctor->specialty }}
            </option>
        @endforeach
    </select>
    @error('doctor_id') <p>{{ $message }}</p> @enderror

    <label>Your name</label>
    <input type="text" name="patient_name" value="{{ old('patient_name') }}" required>
    @error('patient_name') <p>{{ $message }}</p> @enderror

    <label>Phone</label>
    <input type="text" name="patient_phone" value="{{ old('patient_phone') }}" required>
    @error('patient_phone') <p>{{ $message }}</p> @enderror

    <label>Date</label>
    <input type="date" name="appointment_date" value="{{ old('appointment_date') }}"
           min="{{ now()->toDateString() }}" required>
    @error('appointment_date') <p>{{ $message }}</p> @enderror

    <label>Time</label>
    <select name="starts_at" required>
        <option value="">Choose a time</option>
        @foreach ($slots as $slot)
            <option value="{{ $slot }}" @selected(old('starts_at') === $slot)>{{ $slot }}</option>
        @endforeach
    </select>
    @error('starts_at') <p>{{ $message }}</p> @enderror

    <label>Reason for the visit (optional)</label>
    <input type="text" name="reason" value="{{ old('reason') }}">

    <button type="submit">Book appointment</button>
</form>
Enter fullscreen mode Exit fullscreen mode

[SCREENSHOT: booking form in his CarePoint clinic demo, doctor list open]

Step 3: store the booking and block double booking

use Illuminate\Validation\Rule;
use Illuminate\Support\Str;

public function store(Request $request)
{
    $data = $request->validate([
        'doctor_id' => ['required', 'exists:doctors,id'],
        'patient_name' => ['required', 'string', 'max:80'],
        'patient_phone' => ['required', 'string', 'max:20'],
        'appointment_date' => ['required', 'date', 'after_or_equal:today'],
        'starts_at' => ['required', Rule::in(self::SLOTS)],
        'reason' => ['nullable', 'string', 'max:255'],
    ]);

    $taken = Appointment::where('doctor_id', $data['doctor_id'])
        ->whereDate('appointment_date', $data['appointment_date'])
        ->where('starts_at', $data['starts_at'])
        ->where('status', 'booked')
        ->exists();

    if ($taken) {
        return back()->withInput()->withErrors([
            'starts_at' => 'That time is already booked with this doctor. Please pick another slot.',
        ]);
    }

    $data['reference'] = 'APT-' . strtoupper(Str::random(6));

    $appointment = Appointment::create($data);

    return redirect()->route('appointments.confirmation', $appointment->reference);
}

public function confirmation(string $reference)
{
    $appointment = Appointment::with('doctor')
        ->where('reference', $reference)
        ->firstOrFail();

    return view('appointments.confirmation', ['appointment' => $appointment]);
}
Enter fullscreen mode Exit fullscreen mode

Read the order of the checks. Validation runs first, so a past date or a time outside clinic hours never reaches the database. The taken check runs second and keeps the form values, so the patient picks another slot instead of starting over. The unique index from step 1 sits behind both checks. If two patients submit the same slot in the same second, the database rejects the second write.

The confirmation view can stay plain:

<h1>Booking confirmed</h1>
<p>Your booking reference is <strong>{{ $appointment->reference }}</strong></p>
<p>{{ $appointment->doctor->name }} ({{ $appointment->doctor->specialty }})</p>
<p>{{ $appointment->appointment_date->format('l, d M Y') }} at {{ $appointment->starts_at }}</p>
<p>Please arrive 10 minutes early and bring this reference with you.</p>
Enter fullscreen mode Exit fullscreen mode

The patient reads the reference over the phone when they call, and staff search by it. That one string removes most of the name confusion at a small clinic desk.

Step 4: the staff list for tomorrow

Reception needs one screen in the morning: who is coming, in time order, with phone numbers. This page defaults to tomorrow and accepts a date and doctor filter:

class StaffAppointmentController extends Controller
{
    public function index(Request $request)
    {
        $date = $request->input('date', now()->addDay()->toDateString());

        $appointments = Appointment::with('doctor')
            ->whereDate('appointment_date', $date)
            ->when($request->filled('doctor_id'),
                fn ($query) => $query->where('doctor_id', $request->doctor_id))
            ->orderBy('starts_at')
            ->get();

        $doctors = Doctor::orderBy('name')->get();

        return view('staff.appointments.index', [
            'appointments' => $appointments,
            'doctors' => $doctors,
            'date' => $date,
        ]);
    }
}
Enter fullscreen mode Exit fullscreen mode

The view is a filter form and a table. The table is the part staff live in, so keep the columns short:

<table>
    <tr>
        <th>Time</th><th>Patient</th><th>Phone</th>
        <th>Doctor</th><th>Reference</th><th>Status</th>
    </tr>
    @forelse ($appointments as $appointment)
        <tr>
            <td>{{ substr($appointment->starts_at, 0, 5) }}</td>
            <td>{{ $appointment->patient_name }}</td>
            <td>{{ $appointment->patient_phone }}</td>
            <td>{{ $appointment->doctor->name }}</td>
            <td>{{ $appointment->reference }}</td>
            <td>{{ $appointment->status }}</td>
        </tr>
    @empty
        <tr><td colspan="6">No appointments on this date.</td></tr>
    @endforelse
</table>
Enter fullscreen mode Exit fullscreen mode

Put this route behind your staff login before the page goes anywhere near a live clinic. In my own clinic work the staff list sits inside the admin panel, and this public tutorial leaves the login out only to keep the code short.

[SCREENSHOT: staff appointment list in his CarePoint clinic demo, one date]

Step 5: test the flow before you call it done

Book 10 appointments through the form, by hand. Spread them across both doctors and three dates. Then run these checks:

  1. Book one slot, then book the same doctor, date, and slot again. The second attempt must return with the "already booked" message, and the database must still hold one row for that slot.
  2. Pick a date in the past by editing the form value. Validation must reject it. The server rule is the test, not the min attribute.
  3. Open the staff list with no filter. It must show tomorrow, in time order.
  4. Filter the staff list by one doctor. The other doctor rows must disappear.
  5. Open a confirmation link, change one character in the reference, and reload. You should get a 404, which proves the reference lookup is exact.

If all 5 checks pass, the core flow is done: a patient can book, a double booking is blocked in two places, and staff can plan the next day from one screen.

What to add next

Two additions cover most of what a growing clinic asks for next. An SMS reminder the evening before the appointment cuts missed visits. It needs a local SMS provider account and a queue job that sends one message per booking. A payment step at booking time needs a gateway account and a refund rule for clinic cancellations. Both sit on top of the tables you already built.

When the page is ready to go online, my earlier tutorial on putting a Laravel website online, step by step, covers the deployment: https://dev.to/mehedirafi/how-to-put-a-laravel-website-online-step-by-step-3oif

The finished version

The finished version of this project, with the admin screens already built, is CarePoint Clinic on my Gumroad store for $19. The tutorial above builds the core flow from scratch. The paid version saves you the admin work: https://mehedirafi.gumroad.com/l/carepoint-clinic


I am Mehedi Mansur Rafi, a freelance Laravel developer (B.Sc. in Computer Science & Engineering). I build hospital, clinic, and small business websites. My full store is at https://mehedirafi.gumroad.com/ and my site is https://mehedimansurrafi.online

Top comments (0)