0% found this document useful (1 vote)
70 views

Laravel CRUD Example

The document provides instructions for setting up a basic CRUD (Create, Read, Update, Delete) application in Laravel including configuring the database, generating a migration and model, creating a resource controller, modifying the model, adding routes, and generating views for listing, creating, editing and showing employees.

Uploaded by

Suryana
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (1 vote)
70 views

Laravel CRUD Example

The document provides instructions for setting up a basic CRUD (Create, Read, Update, Delete) application in Laravel including configuring the database, generating a migration and model, creating a resource controller, modifying the model, adding routes, and generating views for listing, creating, editing and showing employees.

Uploaded by

Suryana
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 19

Laravel CRUD Example

1. Konfigurasi Database
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=nama_database
DB_USERNAME=root
DB_PASSWORD=

2. Migration dan Model

php artisan make:model Employee --migration

Selanjutnya buka folder migrations yang ada di direktori direktori-laravel-anda/database/migrations lalu modifikasi skema field pada create_employees
_table.php seperti kode di bawah ini :
<?php

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

class CreateEmployeeModelsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('employees, function (Blueprint $table) {
$table->id();
            $table->string('emp_id');
            $table->string('emp_name');
            $table->string('position');
            $table->string('emp_email');
            $table->string('emp_phone');
            $table->text('emp_address');
            $table->timestamps();
        });
    }

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

Jika sudah kita jalankan command di bawah ini agar field yang kita buat akan ter-migrasi ke database:

php artisan migrate

3. Resource Controller

php artisan make:controller EmployeeController --resource

Jika berhasil maka akan terdapat file EmployeeController.php di dalam direktori app/Http/Controllers.

Dalam EmployeeController.php sudah tersedia beberapa function, yaitu:


 index()
 create()
 store()
 show()
 edit()
 destroy()
Sekarang kita modifikasi isi file tersebut seperti kode di bawah ini:
<?php

namespace App\Http\Controllers;

use App\Models\EmployeeModel;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
class EmployeeController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        //mengambil semua record pada tabel employees
        $employees = EmployeeModel::all();
        return view('employees.index', ['employees' => $employees]);
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        //menampilkan halaman create
        return view('employees.create');
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        //validasi input data employee
        $request->validate([
            'emp_id' => ['required', 'string', 'max:10','unique:employee_models'],
            'emp_name' => ['required', 'string', 'max:100'],
            'position' => ['required', 'string', 'max:100'],
            'emp_email' =>['required', 'string', 'email', 'max:50', 'unique:employee_models'],
            'emp_phone' => ['required', 'string', 'max:15','unique:employee_models'],
            'emp_address' => 'required',
        ]);

        //insert setiap request dari form ke dalam database
        //Jika menggunakan metode ini, nama field pada tabel dan form harus sama
        EmployeeModel::create($request->all());

        /// redirect jika sukses menyimpan data
        return redirect()->route('employees.index')
                        ->with('success','Employee Data saved successfully.');

    }

    /**
     * Display the specified resource.
     *
     * @param  \App\Models\EmployeeModel  $employeeModel
     * @return \Illuminate\Http\Response
     */
    public function show(EmployeeModel $employee)
    {
        // dengan menggunakan resource, kita bisa memanfaatkan model sebagai parameter
        // berdasarkan id yang dipilih
        // href="{{ route('employee.show',$employeeModel->id) }}
        return view('employees.show',compact('employee'));
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  \App\Models\EmployeeModel  $employeeModel
     * @return \Illuminate\Http\Response
     */
    public function edit(EmployeeModel $employee)
    {
        /// dengan menggunakan resource, kita bisa memanfaatkan model sebagai parameter
        /// berdasarkan id yang dipilih
        /// href="{{ route('employees.edit',$employee->id) }}
        return view('employees.edit',compact('employee'));
    }
    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \App\Models\EmployeeModel  $employeeModel
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, EmployeeModel $employee)
    {
        //validasi update data employee
        $request->validate([
            'emp_id' => ['required', 'string', 'max:10'],
            'emp_name' => ['required', 'string', 'max:100'],
            'position' => ['required', 'string', 'max:50'],
            'emp_email' =>['required', 'string', 'email', 'max:50'],
            'emp_phone' => ['required', 'string', 'max:15'],
            'emp_address' => 'required',
        ]);

        /// mengubah data berdasarkan request dan parameter yang dikirimkan
        $employee->update($request->all());

        /// setelah berhasil mengubah data
        return redirect()->route('employees.index')
                        ->with('success','Employee data updated successfully');

    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  \App\Models\EmployeeModel  $employeeModel
     * @return \Illuminate\Http\Response
     */
    public function destroy(EmployeeModel $employee)
    {
        /// melakukan hapus data berdasarkan parameter yang dikirimkan
        $employee->delete();

        return redirect()->route('employees.index')
                        ->with('success','Employee data deleted successfully');
    }
}

4. Modifikasi Model
    protected $fillable = [
        'emp_id',
        'emp_name',
        'position',
        'emp_email',
        'emp_phone',
        'emp_address'
    ];

5. Tambahkan Route
use App\Http\Controllers\EmployeeController;
Route::resource('employees', EmployeeController::class);

6. Buat halaman view


Buat folder employees di dalam views
Kemudian buat file-file berikut :
 index.blade.php
 create.blade.php
 show.blade.php
 edit.blade.php
Index.blade.php
<x-app-layout>
    <x-slot name="header">
        <h2 class="font-semibold text-xl text-gray-800 leading-tight">
            {{ __('Employees') }}
        </h2>
    </x-slot>

    <div class="py-12">
        <div class="max-w-7xl mx-auto sm:px-6 lg:px-8">
            <div class="bg-white overflow-hidden shadow-sm sm:rounded-lg">
                <div class="p-6 bg-white border-b border-gray-200">
                    <a href="{{ route('employees.create') }}">
                        <x-button class="mb-4 bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded">
                            {{ __('Add Employee') }}
                        </x-button>
                    </a>

                <!-- This example requires Tailwind CSS v2.0+ -->
                <div class="flex flex-col">
                    <div class="-my-2 overflow-x-auto sm:-mx-6 lg:-mx-8">
                    <div class="py-2 align-middle inline-block min-w-full sm:px-6 lg:px-8">
                        <div class="shadow overflow-hidden border-b border-gray-200 sm:rounded-lg">
                        <table class="min-w-full divide-y divide-gray-200">
                            <thead class="bg-gray-50">
                            <tr>
                                <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase trac
king-wider">
                                Emp. Id
                                </th>
                                <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase trac
king-wider">
                                Name
                                </th>
                                <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase trac
king-wider">
                                Position
                                </th>
                                <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase trac
king-wider">
                                Email
                                </th>
                                <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase trac
king-wider">
                                Phone
                                </th>
                                <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase trac
king-wider">
                                Address
                                </th>
                                <th colspan="2" >

                                </th>
                            </tr>
                            </thead>
                            <tbody class="bg-white divide-y divide-gray-200">
                                @foreach ($employees as $employee )

                            <tr>
                                <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                                    {{ $employee->emp_id }}
                                </td>
                                <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                                    {{ $employee->emp_name }}
                                </td>
                                <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                                    {{ $employee->position }}
                                </td>
                                <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                                    {{ $employee->emp_email }}
                                </td>
                                <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                                    {{ $employee->emp_phone }}
                                </td>
                                <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                                    {{ $employee->emp_address }}
                                </td>
                                <td>
                                    <a href="{{ route('employees.show', $employee->id) }}">
                                        <x-button>
                                            {{ __('Show') }}
                                        </x-button>
                                    </a>
                                    <a href="{{ route('employees.edit', $employee->id) }}">
                                        <x-button>
                                            {{ __('Edit') }}
                                        </x-button>
                                    </a>

                                    <form class="inline-block" method="POST" action="{{ url('employees', $employee->id ) }
}">
                                        @csrf
                                        @method('DELETE')
                                        <x-button onclick="return confirm('Apakah Anda yakin ingin menghapus data ini?')">
                                            {{ __('Delete') }}
                                        </x-button>
                                    </form>

                                </td>
                            </tr>

                            @endforeach
                            </tbody>
                        </table>
                        </div>
                    </div>
                    </div>
                </div>

                </div>
            </div>
        </div>
    </div>

</x-app-layout>

show.blade.php
<x-app-layout>
    <x-slot name="header">
        <h2 class="font-semibold text-xl text-gray-800 leading-tight">
            {{ __('Employees') }}
        </h2>
    </x-slot>
    <div class="py-5">
        <div class="max-w-7xl mx-auto sm:px-6 lg:px-8">
            <div class="bg-white overflow-hidden shadow-sm sm:rounded-lg">
                <div class="p-6 bg-white border-b border-gray-200">

                    <div class="container mx-auto">

                            <div class="text-right">
                                <a href="{{ route('employees.index') }}">
                                    <x-button class="mb-4">
                                        {{ __('Back') }}
                                    </x-button>
                                </a>
                            </div>

                                <div class="grid lg:grid-cols-2 gap-4">
                                    <!-- Emp ID -->
                                    <div>
                                        <x-label for="emp_id" :value="__('Employee ID')" />

                                        <x-input id="emp_id" class="block mt-1 w-full" type="text" name="emp_id" value="{{ 
$employee->emp_id }}" readonly />
                                    </div>

                                    <!-- Name -->
                                    <div>
                                        <x-label for="emp_name" :value="__('Name')" />
                                        <x-input id="emp_name" class="block mt-1 w-full" type="text" name="emp_name" valu
e="{{ $employee->emp_name }}" readonly />
                                    </div>
                                    <!-- Position -->
                                    <div class="mt-4">
                                        <x-label for="position" :value="__('Position')" />
                                        <x-input id="position" class="block mt-1 w-full" type="text" name="position" valu
e="{{ $employee->position }}" readonly />
                                    </div>

                                    <!-- Email-->
                                    <div class="mt-4">
                                        <x-label for="emp_email" :value="__('Email')" />
                                        <x-input id="emp_email" class="block mt-1 w-full" type="email" name="emp_email" val
ue="{{ $employee->emp_email }}" readonly />
                                    </div>

                                    <!-- phone-->
                                    <div class="mt-4">
                                        <x-label for="emp_phone" :value="__('Phone Number')" />
                                        <x-input id="emp_phone" class="block mt-1 w-full" type="text" name="emp_phone" valu
e="{{ $employee->emp_phone }}" readonly />
                                    </div>

                                    <!-- address-->
                                    <div class="mt-4">
                                        <x-label for="emp_address" :value="__('Address')" />
                                        <x-input id="emp_address" class="block mt-1 w-full" type="text" name="emp_address" 
value="{{ $employee->emp_address }}" readonly />
                                    </div>

                                </div>

                    </div>
                </div>
            </div>
        </div>
    </div>
</x-app-layout>

create.blade.php
<x-app-layout>
    <x-slot name="header">
        <h2 class="font-semibold text-xl text-gray-800 leading-tight">
            {{ __('Employees') }}
        </h2>
    </x-slot>

    <div class="py-5">
        <div class="max-w-7xl mx-auto sm:px-6 lg:px-8">
            <div class="bg-white overflow-hidden shadow-sm sm:rounded-lg">
                <div class="p-6 bg-white border-b border-gray-200">

                    <div class="container mx-auto">
                        @if ($errors->any())

                            <div class="mb-3 bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded relative" rol
e="alert">
                                <strong>Whoops!</strong> There were some problems with your input.<br><br>
                                <ul>
                                    @foreach ($errors->all() as $error)
                                        <li>{{ $error }}</li>
                                    @endforeach
                                </ul>
                              </div>
                        @endif

                            <div class="text-right">
                                <a href="{{ route('employees.index') }}">
                                    <x-button class="mb-4">
                                        {{ __('Back') }}
                                    </x-button>
                                </a>
                            </div>

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

                                <div class="grid lg:grid-cols-2 gap-4">
                                    <!-- Emp ID -->
                                    <div>
                                        <x-label for="emp_id" :value="__('Employee ID')" />

                                        <x-input id="emp_id" class="block mt-1 w-full" type="text" name="emp_id" :valu
e="old('emp_id')" required autofocus />
                                    </div>

                                    <!-- Name -->
                                    <div>
                                        <x-label for="emp_name" :value="__('Name')" />
                                        <x-input id="emp_name" class="block mt-1 w-full" type="text" name="emp_name" :valu
e="old('emp_name')" required />
                                    </div>

                                    <!-- Position -->
                                    <div class="mt-4">
                                        <x-label for="position" :value="__('Position')" />
                                        <x-input id="position" class="block mt-1 w-full" type="text" name="position" :valu
e="old('position')" required />
                                    </div>

                                    <!-- Email-->
                                    <div class="mt-4">
                                        <x-label for="emp_email" :value="__('Email')" />
                                        <x-input id="emp_email" class="block mt-1 w-full" type="email" name="emp_email" :va
lue="old('emp_email')" required />
                                    </div>

                                    <!-- phone-->
                                    <div class="mt-4">
                                        <x-label for="emp_phone" :value="__('Phone Number')" />
                                        <x-input id="emp_phone" class="block mt-1 w-full" type="text" name="emp_phone" :val
ue="old('emp_phone')" required />
                                    </div>

                                    <!-- address-->
                                    <div class="mt-4">
                                        <x-label for="emp_address" :value="__('Address')" />
                                        <x-input id="emp_address" class="block mt-1 w-full" type="text" name="emp_address" 
:value="old('emp_address')" required />
                                    </div>

                                </div>
                                <div class="text-right">
                                   <x-button class="mt-4 ">
                                    {{ __('Save') }}
                                </x-button>
                                </div>
                            </form>
                    </div>
                </div>
            </div>
        </div>
    </div>
</x-app-layout>

edit.blade.php
<x-app-layout>
    <x-slot name="header">
        <h2 class="font-semibold text-xl text-gray-800 leading-tight">
            {{ __('Employees') }}
        </h2>
    </x-slot>

    <div class="py-5">
        <div class="max-w-7xl mx-auto sm:px-6 lg:px-8">
            <div class="bg-white overflow-hidden shadow-sm sm:rounded-lg">
                <div class="p-6 bg-white border-b border-gray-200">

                    <div class="container mx-auto">

                        @if ($errors->any())

                            <div class="mb-3 bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded relative" rol
e="alert">
                                <strong>Whoops!</strong> There were some problems with your input.<br><br>
                                <ul>
                                    @foreach ($errors->all() as $error)
                                        <li>{{ $error }}</li>
                                    @endforeach
                                </ul>
                              </div>
                        @endif

                            <div class="text-right">
                                <a href="{{ route('employees.index') }}">
                                    <x-button class="mb-4">
                                        {{ __('Back') }}
                                    </x-button>
                                </a>
                            </div>
                            <form action="{{ route('employees.update',$employee->id) }}" method="POST">
                                @csrf
                                @method('PUT')
                                <div class="grid lg:grid-cols-2 gap-4">
                                    <!-- Emp ID -->
                                    <div>
                                        <x-label for="emp_id" :value="__('Employee ID')" />

                                        <x-input id="emp_id" class="block mt-1 w-full" type="text" name="emp_id" value="{{ 
$employee->emp_id }}" required />
                                    </div>

                                    <!-- Name -->
                                    <div>
                                        <x-label for="emp_name" :value="__('Name')" />
                                        <x-input id="emp_name" class="block mt-1 w-full" type="text" name="emp_name" valu
e="{{ $employee->emp_name }}" required />
                                    </div>

                                    <!-- Position -->
                                    <div class="mt-4">
                                        <x-label for="position" :value="__('Position')" />
                                        <x-input id="position" class="block mt-1 w-full" type="text" name="position" valu
e="{{ $employee->position }}" required />
                                    </div>

                                    <!-- Email-->
                                    <div class="mt-4">
                                        <x-label for="emp_email" :value="__('Email')" />
                                        <x-input id="emp_email" class="block mt-1 w-full" type="email" name="emp_email" val
ue="{{ $employee->emp_email }}" required />
                                    </div>

                                    <!-- phone-->
                                    <div class="mt-4">
                                        <x-label for="emp_phone" :value="__('Phone Number')" />
                                        <x-input id="emp_phone" class="block mt-1 w-full" type="text" name="emp_phone" valu
e="{{ $employee->emp_phone }}" required />
                                    </div>

                                    <!-- address-->
                                    <div class="mt-4">
                                        <x-label for="emp_address" :value="__('Address')" />
                                        <x-input id="emp_address" class="block mt-1 w-full" type="text" name="emp_address" 
value="{{ $employee->emp_address }}" required />
                                    </div>

                                </div>

                                <div class="text-right">
                                    <x-button class="mt-4 ">
                                     {{ __('Update') }}
                                 </x-button>
                                 </div>
                            </form>

                    </div>

                </div>
            </div>
        </div>
    </div>
</x-app-layout>

7. Coba jalankan setiap langkah yang dilakukan.

Referensi :
 https://www.wahyunanangwidodo.com/2021/04/tutorial-crud-laravel-8-mysql-database.html
 Laravel Docs
 Tailwind CSS Docs

You might also like