BelajarKoding Logobelajarkoding

Platform belajar web development Indonesia. Artikel, cheat sheets, roadmap, dan code challenges untuk developer Indonesia.

Navigasi

  • Artikel
  • Cheat Sheets
  • Roadmap
  • Challenges
  • Pricing
  • Search

Produk Lain

  • JagoHermes
  • KelasClaude
  • KilatKoding
  • BelajarVibeCoding
  • JualanKoding

Support

  • Privacy Policy
  • Terms of Service
  • Email

© 2026 BelajarKoding. All rights reserved.

Galih PratamaBagian dari ekosistem Galih Pratama
belajarkoding LogobyGalih Pratama
RoadmapArtikelCheat SheetsChallengesUpgrade
belajarkoding LogobyGalih Pratama
RoadmapArtikelCheat SheetsChallengesUpgrade
belajarkoding LogobyGalih Pratama
RoadmapArtikelCheat SheetsChallengesUpgrade

Daftar Isi

Getting StartedSystem RequirementsInstallationEnvironment ConfigurationConfigurationAccessing ConfigDebug ModeMaintenance ModeRoutingBasic RoutesRoute ParametersNamed RoutesRoute GroupsRoute Model BindingControllersCreating ControllersBasic ControllerResource ControllerRequests & ValidationAccessing Request DataCSRF ProtectionFile UploadsValidationCommon Validation RulesCustom Validation MessagesDisplaying Validation ErrorsViews & BladeCreating ViewsBlade DirectivesLoopsLayouts & SectionsComponentsDatabase & EloquentMigrationsCreating ModelsEloquent QueriesCreating & UpdatingDeletingRelationshipsSession ManagementStoring DataRetrieving DataChecking & DeletingLoggingArtisan CommandsDeploymentOptimizationEnvironment
LaravelPHPBackend

Laravel Cheat Sheet

Referensi cepat Laravel framework. Dari routing, controller, sampe deployment. Perfect buat yang pake Laravel sehari-hari.

PHP10 min read1.909 kata
Silakan login atau daftar untuk membaca cheat sheet ini.

#Getting Started

Panduan awal untuk mulai menggunakan Laravel framework dengan semua setup yang diperlukan.

#System Requirements

Persyaratan sistem yang harus terpenuhi sebelum menginstall Laravel.

bash
# PHP 8.1+ dan extensions yang diperluin:
# - BCMath
# - Ctype
# - JSON
# - Mbstring
# - OpenSSL
# - PDO
# - Tokenizer
# - XML

#Installation

Cara menginstall Laravel menggunakan Composer atau Laravel Sail.

bash
# Via Composer
composer create-project laravel/laravel example-app
 
# Masuk ke folder
cd example-app
 
# Jalanin development server
php artisan serve
 
# Dengan Laravel Sail (Docker)
./vendor/bin/sail up

#Environment Configuration

Konfigurasi environment dan database untuk aplikasi Laravel.

bash
# Copy .env example
cp .env.example .env
 
# Generate application key
php artisan key:generate
 
# Konfigurasi database di .env
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel
DB_USERNAME=root
DB_PASSWORD=

#Configuration

Cara mengelola konfigurasi aplikasi Laravel.

#Accessing Config

Cara mengakses dan mengubah nilai konfigurasi.

php
// Ambil nilai config
$value = config('app.name');
 
// Ambil dengan nilai default
$value = config('app.timezone', 'Asia/Jakarta');
 
// Set config saat runtime
config(['app.locale' => 'id']);

#Debug Mode

Konfigurasi mode debug untuk development dan production.

php
// .env file
APP_DEBUG=true // Development
APP_DEBUG=false // Production

#Maintenance Mode

Cara mengaktifkan mode maintenance untuk downtime aplikasi.

bash
# Aktifin maintenance mode
php artisan down
 
# Dengan pesan custom
php artisan down --message="Lagi maintenance bentar" --retry=60
 
# Matiin maintenance mode
php artisan up

#Routing

Sistem routing Laravel untuk menangani HTTP requests.

#Basic Routes

Cara mendefinisikan route dasar dengan berbagai HTTP methods.

php
use Illuminate\Support\Facades\Route;
 
// Route GET
Route::get('/users', function () {
  return 'Users list';
});
 
// Route POST
Route::post('/users', function () {
  // Create user
});
 
// Route PUT/PATCH
Route::put('/users/{id}', function ($id) {
  // Update user
});
 
// Route DELETE
Route::delete('/users/{id}', function ($id) {
  // Hapus user
});
 
// Multiple method
Route::match(['get', 'post'], '/users', function () {
  //
});
 
// Semua HTTP method
Route::any('/users', function () {
  //
});

#Route Parameters

Cara menangkap parameter dari URL dan memberikan constraints.

php
// Parameter wajib
Route::get('/users/{id}', function ($id) {
  return "User ID: $id";
});
 
// Parameter opsional
Route::get('/users/{name?}', function ($name = 'Guest') {
  return "Hello, $name";
});
 
// Banyak parameter
Route::get('/posts/{post}/comments/{comment}', function ($postId, $commentId) {
  //
});
 
// Constraint regex
Route::get('/users/{id}', function ($id) {
  //
})->where('id', '[0-9]+');
 
Route::get('/users/{name}', function ($name) {
  //
})->where('name', '[A-Za-z]+');

#Named Routes

Cara memberikan nama pada route untuk kemudahan referensi.

php
// Bikin named route
Route::get('/dashboard', function () {
  //
})->name('dashboard');
 
// Generate URL
$url = route('dashboard');
 
// Redirect to named route
return redirect()->route('dashboard');
 
// Dengan parameter
Route::get('/users/{id}', function ($id) {
  //
})->name('users.show');
 
$url = route('users.show', ['id' => 1]);

#Route Groups

Cara mengelompokkan route dengan shared attributes seperti middleware atau prefix.

php
// Group middleware
Route::middleware(['auth'])->group(function () {
  Route::get('/dashboard', function () {
    //
  });
});
 
// Group dengan prefix
Route::prefix('admin')->group(function () {
  Route::get('/users', function () {
    // /admin/users
  });
});
 
// Prefix nama
Route::name('admin.')->group(function () {
  Route::get('/users', function () {
    //
  })->name('users'); // admin.users
});
 
// Gabungan
Route::middleware(['auth'])
  ->prefix('admin')
  ->name('admin.')
  ->group(function () {
    Route::get('/dashboard', function () {
      //
    })->name('dashboard'); // admin.dashboard
  });

#Route Model Binding

Cara otomatis binding model dari route parameters.

php
// Binding otomatis
Route::get('/users/{user}', function (App\Models\User $user) {
  return $user->email;
});
 
// Key custom
Route::get('/posts/{post:slug}', function (App\Models\Post $post) {
  return $post;
});
 
// Binding custom in RouteServiceProvider
public function boot()
{
  Route::model('user', User::class);
 
  Route::bind('user', function ($value) {
    return User::where('name', $value)->firstOrFail();
  });
}

#Controllers

Cara mengorganisir logic aplikasi dalam controller classes.

#Creating Controllers

Cara membuat controller menggunakan artisan commands.

bash
# Basic controller
php artisan make:controller UserController
 
# Resource controller
php artisan make:controller UserController --resource
 
# API resource controller
php artisan make:controller UserController --api

#Basic Controller

php
namespace App\Http\Controllers;
 
use App\Models\User;
use Illuminate\Http\Request;
 
class UserController extends Controller
{
  public function index()
  {
    $users = User::all();
    return view('users.index', compact('users'));
  }
 
  public function show($id)
  {
    $user = User::findOrFail($id);
    return view('users.show', compact('user'));
  }
}

#Resource Controller

php
// Route
Route::resource('users', UserController::class);
 
// Generated routes:
// GET /users - index()
// GET /users/create - create()
// POST /users - store()
// GET /users/{user} - show()
// GET /users/{user}/edit - edit()
// PUT/PATCH /users/{user} - update()
// DELETE /users/{user} - destroy()

#Requests & Validation

#Accessing Request Data

php
use Illuminate\Http\Request;
 
Route::post('/users', function (Request $request) {
  // Get single value
  $name = $request->input('name');
 
  // With default
  $name = $request->input('name', 'Guest');
 
  // Get all input
  $input = $request->all();
 
  // Only specific fields
  $input = $request->only(['name', 'email']);
 
  // Except specific fields
  $input = $request->except(['password']);
 
  // Check if input exists
  if ($request->has('name')) {
    //
  }
});

#CSRF Protection

html
<!-- In forms -->
<form method="POST" action="/users">
  @csrf
  <!-- form fields -->
</form>
php
// Exclude routes from CSRF (in app/Http/Middleware/VerifyCsrfToken.php)
protected $except = [
  'stripe/*',
  'webhook/*',
];

#File Uploads

php
Route::post('/upload', function (Request $request) {
  // Cek apakah file ada
  if ($request->hasFile('photo')) {
    $file = $request->file('photo');
 
    // Simpan file
    $path = $file->store('photos');
    $path = $file->store('photos', 's3'); // disk berbeda
 
    // Simpan dengan nama custom
    $path = $file->storeAs('photos', 'filename.jpg');
 
    // Ambil info file
    $extension = $file->extension();
    $size = $file->getSize();
    $originalName = $file->getClientOriginalName();
  }
});

#Validation

php
Route::post('/users', function (Request $request) {
  $validated = $request->validate([
    'name' => 'required|max:255',
    'email' => 'required|email|unique:users',
    'password' => 'required|min:8|confirmed',
    'age' => 'required|integer|min:18',
    'website' => 'nullable|url',
    'avatar' => 'nullable|image|max:2048',
  ]);
 
  // Data is valid, create user
  User::create($validated);
});

#Common Validation Rules

php
// Field wajib
'name' => 'required'
 
// Email
'email' => 'email'
 
// Unique di database
'email' => 'unique:users,email'
 
// Min/Max
'password' => 'min:8|max:20'
'age' => 'integer|min:18|max:100'
 
// Confirmed (field password_confirmation)
'password' => 'confirmed'
 
// Validasi file
'avatar' => 'image|mimes:jpg,png|max:2048'
 
// Validasi tanggal
'birth_date' => 'date|before:today'
'start_date' => 'date|after:tomorrow'
 
// Array
'tags' => 'array|min:1|max:5'
'tags.*' => 'string|max:50'
 
// Boolean
'accept_terms' => 'required|boolean'
 
// Di dalam array
'role' => 'in:admin,editor,viewer'
 
// Regular expression
'username' => 'regex:/^[a-zA-Z0-9_]+$/'

#Custom Validation Messages

php
$request->validate([
  'name' => 'required|max:255',
  'email' => 'required|email',
], [
  'name.required' => 'Nama harus diisi dong!',
  'email.required' => 'Email jangan lupa!',
  'email.email' => 'Format email salah nih.',
]);

#Displaying Validation Errors

html
@if ($errors->any())
  <div class="alert alert-danger">
    <ul>
      @foreach ($errors->all() as $error)
        <li>{{ $error }}</li>
      @endforeach
    </ul>
  </div>
@endif
 
<!-- Single field error -->
@error('email')
  <div class="alert">{{ $message }}</div>
@enderror

#Views & Blade

#Creating Views

php
// Return view
return view('welcome');
 
// With data
return view('users.profile', ['name' => 'John']);
 
// Or use compact
$name = 'John';
return view('users.profile', compact('name'));
 
// With method
return view('users.profile')->with('name', 'John');

#Blade Directives

html
<!-- Variables -->
<h1>Hello, {{ $name }}</h1>
 
<!-- Unescaped (hati-hati XSS!) -->
{!! $html !!}
 
<!-- Comments -->
{{-- This is a comment --}}
 
<!-- Conditionals -->
@if ($user->isAdmin())
  <p>Admin user</p>
@elseif ($user->isModerator())
  <p>Moderator</p>
@else
  <p>Regular user</p>
@endif
 
<!-- Unless -->
@unless ($user->isAdmin())
  <p>Not an admin</p>
@endunless
 
<!-- Isset & Empty -->
@isset($name)
  <p>Name is set</p>
@endisset
 
@empty($records)
  <p>No records</p>
@endempty
 
<!-- Authentication -->
@auth
  <p>User is logged in</p>
@endauth
 
@guest
  <p>Please login</p>
@endguest

#Loops

html
<!-- Foreach -->
@foreach ($users as $user)
  <p>{{ $user->name }}</p>
@endforeach
 
<!-- For -->
@for ($i = 0; $i < 10; $i++)
  <p>Number {{ $i }}</p>
@endfor
 
<!-- While -->
@while (true)
  <p>Looping...</p>
@endwhile
 
<!-- Forelse (with empty check) -->
@forelse ($users as $user)
  <p>{{ $user->name }}</p>
@empty
  <p>No users found</p>
@endforelse
 
<!-- Loop variable -->
@foreach ($users as $user)
  @if ($loop->first)
    <p>First iteration</p>
  @endif
 
  <p>{{ $loop->index }}: {{ $user->name }}</p>
 
  @if ($loop->last)
    <p>Last iteration</p>
  @endif
@endforeach

#Layouts & Sections

html
<!-- resources/views/layouts/app.blade.php -->
<!DOCTYPE html>
<html>
<head>
  <title>@yield('title', 'Default Title')</title>
</head>
<body>
  @yield('content')
 
  @stack('scripts')
</body>
</html>
 
<!-- resources/views/users/profile.blade.php -->
@extends('layouts.app')
 
@section('title', 'User Profile')
 
@section('content')
  <h1>User Profile</h1>
  <p>Welcome, {{ $name }}</p>
@endsection
 
@push('scripts')
  <script src="/js/profile.js"></script>
@endpush

#Components

html
<!-- Include subview -->
@include('partials.header')
 
<!-- With data -->
@include('partials.user-card', ['user' => $user])

#Database & Eloquent

#Migrations

bash
# Create migration
php artisan make:migration create_users_table
 
# Run migrations
php artisan migrate
 
# Rollback
php artisan migrate:rollback
 
# Reset (rollback semua)
php artisan migrate:reset
 
# Fresh (drop semua table + migrate)
php artisan migrate:fresh
 
# Refresh (rollback + migrate)
php artisan migrate:refresh

#Creating Models

bash
# Model aja
php artisan make:model User
 
# Model + migration
php artisan make:model User -m
 
# Model + migration + controller
php artisan make:model User -mc
 
# Model + migration + controller + resource
php artisan make:model User -mcr
 
# All (migration, factory, seeder, controller)
php artisan make:model User --all

#Eloquent Queries

php
use App\Models\User;
 
// Get all
$users = User::all();
 
// Find by ID
$user = User::find(1);
$user = User::findOrFail(1); // Throw exception if not found
 
// Where clauses
$users = User::where('active', 1)->get();
$users = User::where('votes', '>', 100)->get();
$users = User::where('name', 'like', '%john%')->get();
 
// Multiple where
$users = User::where('active', 1)
  ->where('votes', '>', 100)
  ->get();
 
// Or where
$users = User::where('votes', '>', 100)
  ->orWhere('name', 'John')
  ->get();
 
// Order by
$users = User::orderBy('name', 'asc')->get();
$users = User::latest()->get(); // Order by created_at desc
$users = User::oldest()->get(); // Order by created_at asc
 
// Limit
$users = User::take(5)->get();
$users = User::limit(5)->get();
 
// First
$user = User::where('active', 1)->first();
$user = User::firstOrFail(); // Throw if not found

#Creating & Updating

php
// Create
$user = User::create([
  'name' => 'John Doe',
  'email' => 'john@example.com',
  'password' => bcrypt('password'),
]);
 
// Find and update
$user = User::find(1);
$user->name = 'Jane Doe';
$user->save();
 
// Mass update
User::where('active', 0)->update(['active' => 1]);
 
// Update or create
User::updateOrCreate(
  ['email' => 'john@example.com'], // Kriteria pencarian
  ['name' => 'John Doe'] // Nilai yang di-update
);

#Deleting

php
// Hapus lewat model
$user = User::find(1);
$user->delete();
 
// Hapus lewat query
User::where('active', 0)->delete();
 
// Destroy pake ID
User::destroy(1);
User::destroy([1, 2, 3]);
User::destroy(1, 2, 3);

#Relationships

php
// One to One
class User extends Model
{
  public function phone()
  {
    return $this->hasOne(Phone::class);
  }
}
 
// One to Many
class Post extends Model
{
  public function comments()
  {
    return $this->hasMany(Comment::class);
  }
}
 
// Belongs To
class Comment extends Model
{
  public function post()
  {
    return $this->belongsTo(Post::class);
  }
}
 
// Many to Many
class User extends Model
{
  public function roles()
  {
    return $this->belongsToMany(Role::class);
  }
}

#Session Management

#Storing Data

php
// Via request
$request->session()->put('key', 'value');
 
// Via helper
session(['key' => 'value']);
 
// Flash data (cuma satu request)
$request->session()->flash('message', 'Data saved!');

#Retrieving Data

php
// Via request
$value = $request->session()->get('key');
$value = $request->session()->get('key', 'default');
 
// Via helper
$value = session('key');
$value = session('key', 'default');
 
// Get all
$data = $request->session()->all();

#Checking & Deleting

php
// Cek apakah ada
if ($request->session()->has('key')) {
  //
}
 
// Hapus
$request->session()->forget('key');
$request->session()->forget(['key1', 'key2']);
 
// Clear semua
$request->session()->flush();

#Logging

php
use Illuminate\Support\Facades\Log;
 
// Log levels
Log::emergency($message);
Log::alert($message);
Log::critical($message);
Log::error($message);
Log::warning($message);
Log::notice($message);
Log::info($message);
Log::debug($message);
 
// With context
Log::info('User login', ['id' => $user->id]);

#Artisan Commands

bash
# List all commands
php artisan list
 
# Help for command
php artisan help migrate
 
# Clear cache
php artisan cache:clear
php artisan config:clear
php artisan route:clear
php artisan view:clear
 
# Optimize
php artisan optimize
php artisan config:cache
php artisan route:cache
php artisan view:cache
 
# Queue
php artisan queue:work
php artisan queue:listen
php artisan queue:restart
 
# Storage link
php artisan storage:link

#Deployment

#Optimization

bash
# Cache config
php artisan config:cache
 
# Cache routes
php artisan route:cache
 
# Cache views
php artisan view:cache
 
# Optimize autoloader
composer install --optimize-autoloader --no-dev
 
# Optimize application
php artisan optimize

#Environment

bash
# Set to production
APP_ENV=production
APP_DEBUG=false
 
# Generate app key (kalo belum)
php artisan key:generate

Baca Cheat Sheet Lengkap

Login atau daftar akun gratis untuk membaca cheat sheet ini.

LoginDaftar Gratis
Share: