CRUD Laravel 9 + Bootstrap5 + MySQL

CRUD Laravel 9

CRUD Laravel 9 – Tutorial Create, Read, Update, dan Delete Laravel 9 dengan Bootstrap 5 dan database MySQL. Kasus kali ini adalah mengolah data pelanggan (Customer).

Membuat Project Laravel

Pastikan Anda sudah menginstall composer, kemudian jalankan perintah berikut di command prompt.

composer create-project laravel/laravel laravel-crud

Mengatur Database MySQL

Buat database dengan nama laravel_crud di http://localhost/phpmyadmin jika Anda menginstall XAMPP untuk server MySQL.

Sesuaikan pengaturan koneksi mysql di project laravel pada file .env

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel_crud
DB_USERNAME=root
DB_PASSWORD=

Sesuaikan DB_HOST, DB_PORT, DB_DATABASE, DB_USERNAME, dan DB_PASSWORD sesuai server MySQL.

Membuat Migration Customer

Laravel 9 sudah menyediakan migration untuk users, password_resets, failed_jobs, dan personal_access_tokens yang ada di direktori database/migrations. Anda bisa menghapus file tersebut dan membuat migration baru dengan perintah berikut.

php artisan make:migration create_tb_customer_table

Kemudian sesuaikan field pada migration sebagai berikut.

<?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('tb_customer', function (Blueprint $table) {
            $table->id('customer_id');
            $table->string('customer_name');
            $table->string('contact_name')->nullable();
            $table->string('address')->nullable();
            $table->string('city')->nullable();
            $table->timestamps();
        });
    }

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

Lakukan migration dengan mengetikan perintah berikut.

php artisan migrate

Setelah berhasil menjalankan perintah migrate, maka di database akan ada tabel tb_customer. Untuk mengisi data bisa menggunakan input manual atau eksekusi perintah sql berikut di phpmyadmin.

INSERT INTO tb_customer VALUES
    (1,'Alfreds Futterkiste','Maria Anders','Obere Str. 57','Berlin','2022-02-12 15:28:07.390000','2022-02-12 15:28:07.390000'),
    (2,'Ana Trujillo Emparedados y helados','Ana Trujillo','Avda. de la Constitución 2222','México D.F.','2022-02-12 15:28:07.390000','2022-02-12 15:28:07.390000'),
    (3,'Antonio Moreno Taquería','Antonio Moreno','Mataderos 2312','México D.F.','2022-02-12 15:28:07.390000','2022-02-12 15:28:07.390000'),
    (4,'Around the Horn','Thomas Hardy','120 Hanover Sq.','London','2022-02-12 15:28:07.390000','2022-02-12 15:28:07.390000'),
    (5,'Berglunds snabbköp','Christina Berglund','Berguvsvägen 8','Luleå','2022-02-12 15:28:07.390000','2022-02-12 15:28:07.390000'),
    (6,'Blauer See Delikatessen','Hanna Moos','Forsterstr. 57','Mannheim','2022-02-12 15:28:07.390000','2022-02-12 15:28:07.390000'),
    (7,'Blondel père et fils','Frédérique Citeaux','24, place Kléber','Strasbourg','2022-02-12 15:28:07.390000','2022-02-12 15:28:07.390000'),
    (8,'Bólido Comidas preparadas','Martín Sommer','C/ Araquil, 67','Madrid','2022-02-12 15:28:07.390000','2022-02-12 15:28:07.390000'),
    (9,'Bon app''','Laurence Lebihans','12, rue des Bouchers','Marseille','2022-02-12 15:28:07.390000','2022-02-12 15:28:07.390000'),
    (10,'Bottom-Dollar Marketse','Elizabeth Lincoln','23 Tsawassen Blvd.','Tsawassen','2022-02-12 15:28:07.390000','2022-02-12 15:28:07.390000'),
    (11,'B''s Beverages','Victoria Ashworth','Fauntleroy Circus','London','2022-02-12 15:28:07.390000','2022-02-12 15:28:07.390000'),
    (12,'Cactus Comidas para llevar','Patricio Simpson','Cerrito 333','Buenos Aires','2022-02-12 15:28:07.390000','2022-02-12 15:28:07.390000'),
    (13,'Centro comercial Moctezuma','Francisco Chang','Sierras de Granada 9993','México D.F.','2022-02-12 15:28:07.390000','2022-02-12 15:28:07.390000'),
    (14,'Chop-suey Chinese','Yang Wang','Hauptstr. 29','Bern','2022-02-12 15:28:07.390000','2022-02-12 15:28:07.390000'),
    (15,'Comércio Mineiro','Pedro Afonso','Av. dos Lusíadas, 23','São Paulo','2022-02-12 15:28:07.390000','2022-02-12 15:28:07.390000'),
    (16,'Consolidated Holdings','Elizabeth Brown','Berkeley Gardens 12 Brewery','London','2022-02-12 15:28:07.390000','2022-02-12 15:28:07.390000'),
    (17,'Drachenblut Delikatessend','Sven Ottlieb','Walserweg 21','Aachen','2022-02-12 15:28:07.390000','2022-02-12 15:28:07.390000'),
    (18,'Du monde entier','Janine Labrune','67, rue des Cinquante Otages','Nantes','2022-02-12 15:28:07.390000','2022-02-12 15:28:07.390000'),
    (19,'Eastern Connection','Ann Devon','35 King George','London','2022-02-12 15:28:07.390000','2022-02-12 15:28:07.390000'),
    (20,'Ernst Handel','Roland Mendel','Kirchgasse 6','Graz','2022-02-12 15:28:07.390000','2022-02-12 15:28:07.390000'),
    (21,'Familia Arquibaldo','Aria Cruz','Rua Orós, 92','São Paulo','2022-02-12 15:28:07.390000','2022-02-12 15:28:07.390000'),
    (22,'FISSA Fabrica Inter. Salchichas S.A.','Diego Roel','C/ Moralzarzal, 86','Madrid','2022-02-12 15:28:07.390000','2022-02-12 15:28:07.390000'),
    (23,'Folies gourmandes','Martine Rancé','184, chaussée de Tournai','Lille','2022-02-12 15:28:07.390000','2022-02-12 15:28:07.390000'),
    (24,'Folk och fä HB','Maria Larsson','Åkergatan 24','Bräcke','2022-02-12 15:28:07.390000','2022-02-12 15:28:07.390000'),
    (25,'Frankenversand','Peter Franken','Berliner Platz 43','München','2022-02-12 15:28:07.390000','2022-02-12 15:28:07.390000');

Membuat Model Customer (Eloquent)

Buat model Customer menggunakan perintah berikut.

php artisan make:model Customer

Sesuaikan app/models/Customer.php sebagai berikut.

<?php

namespace App\Models;

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

class Customer extends Model
{
    use HasFactory;

    protected $table = 'tb_customer';
    protected $primaryKey = 'customer_id';
    protected $fillable = ['customer_name', 'contact_name', 'address', 'city'];
}

Properti $table untuk mengatur nama tabel di database, jika nama tabel anda customers, tidak usah mengubah properti ini.

Properti $primaryKey untuk mengatur PRIMARY KEY di tabel customer, jika primary key anda id, tidak usah mengubah properti ini.

Properti $fillable untuk mengatur field apa saja yang bisa diinput/ubah ketika melakukan crud di tabel customer.

Membuat Controller Customer Tipe Resource

Gunakan perintah berikut untuk membuat controller resource sekaligus mengatur model menjadi Customer.

php artisan make:controller CustomerController --model=Customer

Sesuaikan app/controllers/CustomerController.php sebagai berikut.

<?php

namespace App\Http\Controllers;

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

class CustomerController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        $data['title'] = 'Customers';
        $data['q'] = $request->get('q');
        $data['customers'] = Customer::where('customer_name', 'like', '%' . $data['q'] . '%')->get();
        return view('customer.index', $data);
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        $data['title'] = 'Add Customer';
        return view('customer.create', $data);
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $request->validate([
            'customer_name' => 'required',
            'contact_name' => 'required',
        ]);

        $customer = new Customer($request->all());
        $customer->save();
        return redirect('customer')->with('success', 'Customer added successfully');
    }

    /**
     * Display the specified resource.
     *
     * @param  \App\Models\Customer  $customer
     * @return \Illuminate\Http\Response
     */
    public function show(Customer $customer)
    {
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  \App\Models\Customer  $customer
     * @return \Illuminate\Http\Response
     */
    public function edit(Customer $customer)
    {
        $data['title'] = 'Edit Customer';
        $data['customer'] = $customer;
        return view('customer.edit', $data);
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \App\Models\Customer  $customer
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, Customer $customer)
    {
        $request->validate([
            'customer_name' => 'required',
            'contact_name' => 'required',
        ]);

        $customer->customer_name = $request->customer_name;
        $customer->contact_name = $request->contact_name;
        $customer->address = $request->address;
        $customer->city = $request->city;
        $customer->save();
        return redirect('customer')->with('success', 'Customer updated succesfully');
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  \App\Models\Customer  $customer
     * @return \Illuminate\Http\Response
     */
    public function destroy(Customer $customer)
    {
        $customer->delete();
        return redirect('customer')->with('success', 'Customer deleted successfully');
    }
}

Menambahkan Route Customer

Tambahkan route untuk crud user di routes/web.php bertipe resource seperti berikut.

<?php

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

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/

Route::get('/', function () {
    return view('welcome');
});

Route::resource('customer', CustomerController::class);

Membuat View

View Template

Buat view untuk template di direktori resources/views/app.blade.php.

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>@yield('title', $title)</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
</head>

<body>
    <div class="container">
        <h1>@yield('title', $title)</h1>
        @yield('content')
    </div>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
</body>

</html>

View Tampil

Buat view untuk menampilkan data customer di direktori resources/views/customer/index.blade.php.

@extends('app')
@section('content')
@if(session('success'))
<p class="alert alert-success">{{ session('success') }}</p>
@endif
<div class="card card-default">
    <div class="card-header">
        <form class="row row-cols-auto g-1">
            <div class="col">
                <input class="form-control" type="text" name="q" value="{{ $q }}" placeholder="Search here..." />
            </div>
            <div class="col">
                <button class="btn btn-success">Refresh</button>
            </div>
            <div class="col">
                <a class="btn btn-primary" href="{{ route('customer.create') }}">Add</a>
            </div>
        </form>
    </div>
    <div class="card-body p-0 table-responsive">
        <table class="table table-bordered table-striped table-hover mb-0">
            <thead>
                <tr>
                    <th>#</th>
                    <th>Customer Name</th>
                    <th>Contact Name</th>
                    <th>Address</th>
                    <th>City</th>
                    <th>Aksi</th>
                </tr>
            </thead>
            <?php $no = 1 ?>
            @foreach($customers as $customer)
            <tr>
                <td>{{ $no++ }}</td>
                <td>{{ $customer->customer_name }}</td>
                <td>{{ $customer->contact_name }}</td>
                <td>{{ $customer->address }}</td>
                <td>{{ $customer->city }}</td>
                <td>
                    <a class="btn btn-sm btn-warning" href="{{ route('customer.edit', $customer) }}">Edit</a>
                    <form method="POST" action="{{ route('customer.destroy', $customer) }}" style="display: inline-block;">
                        @csrf
                        @method('DELETE')
                        <button class="btn btn-sm btn-danger" onclick="return confirm('Delete?')">Delete</button>
                    </form>
                </td>
            </tr>
            @endforeach
        </table>
    </div>
</div>
@endsection

View Tambah

Buat view untuk menambah data customer di direktori resources/views/customer/create.blade.php.

@extends('app')
@section('content')
<div class="row">
    <div class="col-md-6">
        @if($errors->any())
        @foreach($errors->all() as $err)
        <p class="alert alert-danger">{{ $err }}</p>
        @endforeach
        @endif
        <form action="{{ route('customer.store') }}" method="POST">
            @csrf
            <div class="mb-3">
                <label>Customer Name <span class="text-danger">*</span></label>
                <input class="form-control" type="text" name="customer_name" value="{{ old('customer_name') }}" />
            </div>
            <div class="mb-3">
                <label>Contact Name <span class="text-danger">*</span></label>
                <input class="form-control" type="text" name="contact_name" value="{{ old('contact_name') }}" />
            </div>
            <div class="mb-3">
                <label>Address</label>
                <input class="form-control" type="text" name="address" value="{{ old('address') }}" />
            </div>
            <div class="mb-3">
                <label>City</label>
                <input class="form-control" type="text" name="city" value="{{ old('city') }}" />
            </div>
            <div class="mb-3">
                <button class="btn btn-primary">Save</button>
                <a class="btn btn-danger" href="{{ route('customer.index') }}">Back</a>
            </div>
        </form>
    </div>
</div>
@endsection

View Ubah

Buat view untuk menambah data customer di direktori resources/views/customer/edit.blade.php.

@extends('app')
@section('content')
<div class="row">
    <div class="col-md-6">
        @if($errors->any())
        @foreach($errors->all() as $err)
        <p class="alert alert-danger">{{ $err }}</p>
        @endforeach
        @endif
        <form action="{{ route('customer.update', $customer) }}" method="POST">
            @csrf
            @method('PUT')
            <div class="mb-3">
                <label>Customer Name <span class="text-danger">*</span></label>
                <input class="form-control" type="text" name="customer_name" value="{{ old('customer_name', $customer->customer_name) }}" />
            </div>
            <div class="mb-3">
                <label>Contact Name <span class="text-danger">*</span></label>
                <input class="form-control" type="text" name="contact_name" value="{{ old('contact_name', $customer->contact_name) }}" />
            </div>
            <div class="mb-3">
                <label>Address</label>
                <input class="form-control" type="text" name="address" value="{{ old('address', $customer->address) }}" />
            </div>
            <div class="mb-3">
                <label>City</label>
                <input class="form-control" type="text" name="city" value="{{ old('city', $customer->city) }}" />
            </div>
            <div class="mb-3">
                <button class="btn btn-primary">Save</button>
                <a class="btn btn-danger" href="{{ route('customer.index') }}">Back</a>
            </div>
        </form>
    </div>
</div>
@endsection

Menjalankan Project

Silahkan gunakan perintah berikut untuk mengaktifkan server laravel.

php artisan serve

Ketikkan alamat sesuai server diikuti dengan /customer di browser (http://127.0.0.1:8000/customer). Hasilnya seperti berikut.

Data Customer
Tambah Customer
Ubah Customer

Itulah tutorial membuat CRUD Laravel 9. Jika ada yang ditanyakan, silahkan berkomentar.

Leave a Comment

Alamat email Anda tidak akan dipublikasikan.

Situs ini menggunakan Akismet untuk mengurangi spam. Pelajari bagaimana data komentar Anda diproses.

To top