Membuat CRUD dengan Laravel for Go + Inertia React (Tutorial Lengkap)

Laravel for Go (go.laravel.com) brings the Laravel developer experience to Go. In this tutorial, we will build a full CRUD (Create, Read, Update, Delete) resource using Go handlers, Inertia v3 + React + TypeScript frontend, and MySQL database — all in idiomatic Go.

Bahasa Indonesia version below.

Apa itu Laravel for Go?

Laravel for Go adalah framework web modern yang dibangun di atas Go, membawa konsep-konsep Laravel PHP (routing, middleware, Eloquent-like models, migrations, Inertia, dll) ke dalam ekosistem Go. Cocok untuk Anda yang suka kecepatan Go namun ingin pengembangan web yang ekspresif dan terstruktur.

Prasyarat

  • Go terinstal (versi terbaru)
  • MySQL database
  • Node.js + npm (untuk frontend Inertia)
  • CLI laravel (opsional, atau gunakan go run .)

Langkah 1: Buat Model dan Migration

Kita akan buat resource Post. Pertama, buat model di models/post.go:

package models import ( "time" ) type Post struct { ID int64 `json:"id"` Title string `json:"title"` Body string `json:"body"` Published bool `json:"published"` CreatedAt time.Time `json:"created_at"` UpdatedAt time.Time `json:"updated_at"` } 

Selanjutnya, buat migration di database/migrations/:

package migrations import ( "context" "go.laravel.com/schema" ) func createPostsTable(ctx context.Context) error { return schema.Create(ctx, "posts", func(table *schema.Blueprint) { table.ID() table.String("title") table.Text("body") table.Boolean("published").Default(false) table.Timestamps() }) } 

Daftarkan migration di database/migrations/migrations.go:

var All = []db.Migration{ {Name: "0001_01_01_000000_create_users_table", Run: createUsersTable}, {Name: "0002_01_01_000000_create_posts_table", Run: createPostsTable}, // ... } 

Jalankan migrasi:

laravel migrate 

Langkah 2: Buat Handler CRUD

Handler di Laravel for Go adalah fungsi biasa dengan tanda tangan func Name(r *web.Request) *web.Response. Buat paket di handlers/post/:

Index — menampilkan daftar post

handlers/post/index.go:

package post import ( "go.laravel.com/db" "go.laravel.com/inertia" "go.laravel.com/web" "app/models" ) func Index(r *web.Request) *web.Response { var posts []models.Post db.From(r).Query().Find(&posts) return inertia.Render("Posts/Index", inertia.Props{ "posts": posts, }) } 

Show — detail satu post

handlers/post/show.go:

package post import ( "go.laravel.com/db" "go.laravel.com/inertia" "go.laravel.com/web" "app/models" ) func Show(r *web.Request) *web.Response { id := r.Route().Parameter("id") var post models.Post db.From(r).Query().First(&post, "id = ?", id) return inertia.Render("Posts/Show", inertia.Props{ "post": post, }) } 

Store — menyimpan post baru

handlers/post/store.go:

package post import ( "go.laravel.com/db" "go.laravel.com/validation" "go.laravel.com/web" "app/models" ) func Store(r *web.Request) *web.Response { data := r.Validate(validation.For{ "title": validation.Required, "body": validation.Required, "published": validation.Boolean, }) post := models.Post{ Title: data.String("title"), Body: data.String("body"), Published: data.Bool("published"), } db.From(r).Query().Create(&post) return web.Redirect("/posts") } 

Update — memperbarui post

handlers/post/update.go:

package post import ( "go.laravel.com/db" "go.laravel.com/validation" "go.laravel.com/web" "app/models" ) func Update(r *web.Request) *web.Response { id := r.Route().Parameter("id") data := r.Validate(validation.For{ "title": validation.Required, "body": validation.Required, "published": validation.Boolean, }) var post models.Post db.From(r).Query().First(&post, "id = ?", id) post.Title = data.String("title") post.Body = data.String("body") post.Published = data.Bool("published") db.From(r).Query().Save(&post) return web.Redirect("/posts") } 

Destroy — menghapus post

handlers/post/destroy.go:

package post import ( "go.laravel.com/db" "go.laravel.com/web" "app/models" ) func Destroy(r *web.Request) *web.Response { id := r.Route().Parameter("id") var post models.Post db.From(r).Query().Delete(&post, "id = ?", id) return web.Redirect("/posts") } 

Create dan Edit — menampilkan form

handlers/post/create.go:

package post import ( "go.laravel.com/inertia" "go.laravel.com/web" ) func Create(r *web.Request) *web.Response { return inertia.Render("Posts/Create") } 

handlers/post/edit.go:

package post import ( "go.laravel.com/db" "go.laravel.com/inertia" "go.laravel.com/web" "app/models" ) func Edit(r *web.Request) *web.Response { id := r.Route().Parameter("id") var post models.Post db.From(r).Query().First(&post, "id = ?", id) return inertia.Render("Posts/Edit", inertia.Props{ "post": post, }) } 

Langkah 3: Daftarkan Routes

Di routes/web.go:

package routes import ( "go.laravel.com/config" "go.laravel.com/routing" "go.laravel.com/web" "app/handlers/post" "app/handlers/welcome" ) func Web(route *routing.Router, cfg *config.Config) { route.Get("/", welcome.Show) route.Resource("posts", post.Resource{ Index: post.Index, Show: post.Show, Create: post.Create, Store: post.Store, Edit: post.Edit, Update: post.Update, Destroy: post.Destroy, }) route.Fallback(func(*web.Request) *web.Response { return web.Abort(http.StatusNotFound) }) } 

Langkah 4: Frontend Inertia (React + TypeScript)

Buat halaman di resources/js/pages/posts/:

Index.tsx

import { Head, usePage } from '@inertiajs/react'; import Link from '@inertiajs/react'; import { useEffect, useState } from 'react'; interface Props { posts: Array<{ id: number; title: string; body: string; published: boolean; created_at: string; updated_at: string; }>; } export default function PostsIndex({ posts }: Props) { return ( <div className="min-h-screen bg-gray-50 p-6"> <Head title="Posts" /> <h1 className="text-2xl font-bold mb-6">Posts</h1> <Link href="/posts/create" className="bg-blue-600 text-white px-4 py-2 rounded mb-4 inline-block"> + Create Post </Link> <table className="w-full border-collapse border border-gray-200"> <thead> <tr className="bg-gray-100"> <th className="border p-2">ID</th> <th className="border p-2">Title</th> <th className="border p-2">Published</th> <th className="border p-2">Actions</th> </tr> </thead> <tbody> {posts.map((post) => ( <tr key={post.id} className="hover:bg-gray-50"> <td className="border p-2">{post.id}</td> <td className="border p-2">{post.title}</td> <td className="border p-2">{post.published ? 'Yes' : 'No'}</td> <td className="border p-2"> <Link href={`/posts/${post.id}`} className="text-blue-600 mr-2">Show</Link> <Link href={`/posts/${post.id}/edit`} className="text-blue-600 mr-2">Edit</Link> <form as="form" method="post" action={`/posts/${post.id}`} data-method="delete" className="inline" > <button type="submit" className="text-red-600" onClick={(e) => { if(!confirm('Delete?')) e.preventDefault(); }}>Delete</button> </form> </td> </tr> ))} </tbody> </table> </div> ); } 

Create.tsx

import { Head, useForm } from '@inertiajs/react'; import { useState } from 'react'; export default function PostsCreate() { const { data, setData, errors, processing, submit } = useForm<any>({ title: '', body: '', published: false, }); return ( <div className="min-h-screen bg-gray-50 p-6"> <Head title="Create Post" /> <h1 className="text-2xl font-bold mb-6">Create Post</h1> <form onSubmit={(e) => { e.preventDefault(); submit({ method: 'post', url: '/posts' }); }} className="space-y-4 max-w-lg" > <div> <label className="block text-sm font-medium">Title</label> <input type="text" className="w-full border rounded p-2" value={data.title} onChange={(e) => setData('title', e.target.value)} /> {errors.title && <p className="text-red-500 text-sm">{errors.title}</p>} </div> <div> <label className="block text-sm font-medium">Body</label> <textarea className="w-full border rounded p-2" value={data.body} onChange={(e) => setData('body', e.target.value)} /> {errors.body && <p className="text-red-500 text-sm">{errors.body}</p>} </div> <div className="flex items-center gap-2"> <input type="checkbox" checked={data.published} onChange={(e) => setData('published', e.target.checked)} /> <label>Published</label> {errors.published && <p className="text-red-500 text-sm">{errors.published}</p>} </div> <button type="submit" disabled={processing} className="bg-blue-600 text-white px-4 py-2 rounded disabled:opacity-50" > Save </button> </form> </div> ); } 

Halaman Edit.tsx dan Show.tsx mengikuti pola yang sama menggunakan usePage().props.post.

Langkah 5: Menjalankan dan Menguji

Jalankan aplikasi:

go run . 

Atau dengan laravel CLI:

laravel serve 

Buka http://localhost:8000/posts.

Menulis Test

Di tests/feature/post_test.go:

package feature_test import ( "testing" "app/tests" ) func TestPostsCRUD(t *testing.T) { client := tests.New(t) client.Get("/posts").AssertOK().AssertInertia("Posts/Index") client.Get("/posts/create").AssertOK().AssertInertia("Posts/Create") client.Post("/posts", map[string]any{ "title": "Hello Laravel for Go", "body": "This is my first post.", "published": true, }).AssertStatus(302) client.Get("/posts/1").AssertOK().AssertInertia("Posts/Show") } 

Jalankan test:

...