Referensi cepat Laravel framework. Dari routing, controller, sampe deployment. Perfect buat yang pake Laravel sehari-hari.
Panduan awal untuk mulai menggunakan Laravel framework dengan semua setup yang diperlukan.
Persyaratan sistem yang harus terpenuhi sebelum menginstall Laravel.
# PHP 8.1+ dan extensions yang diperluin:
# - BCMath
# - Ctype
# - JSON
# - Mbstring
# - OpenSSL
# - PDO
# - Tokenizer
# - XMLCara menginstall Laravel menggunakan Composer atau Laravel Sail.
# 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 upKonfigurasi environment dan database untuk aplikasi Laravel.
# 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
Cara mengelola konfigurasi aplikasi Laravel.
Cara mengakses dan mengubah nilai konfigurasi.
// 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']);Konfigurasi mode debug untuk development dan production.
// .env file
APP_DEBUG=true // Development
APP_DEBUG=false // ProductionCara mengaktifkan mode maintenance untuk downtime aplikasi.
# Aktifin maintenance mode
php artisan down
# Dengan pesan custom
php artisan down --message="Lagi maintenance bentar" --retry=60
# Matiin maintenance mode
php artisan upSistem routing Laravel untuk menangani HTTP requests.
Cara mendefinisikan route dasar dengan berbagai HTTP methods.
use Illuminate\Support\Facades\Route;
// Route GET
Route::get('/users', function () {
return 'Users list';
});
// Route POST
Route::post('/users'
Cara menangkap parameter dari URL dan memberikan constraints.
// Parameter wajib
Route::get('/users/{id}', function ($id) {
return "User ID: $id";
});
// Parameter opsional
Route::get('/users/{name?}', function
Cara memberikan nama pada route untuk kemudahan referensi.
// Bikin named route
Route::get('/dashboard', function () {
//
})->name('dashboard');
// Generate URL
$url = route('dashboard');
// Redirect to named route
Cara mengelompokkan route dengan shared attributes seperti middleware atau prefix.
// Group middleware
Route::middleware(['auth'])->group(function () {
Route::get('/dashboard', function () {
//
});
Cara otomatis binding model dari route parameters.
// Binding otomatis
Route::get('/users/{user}', function (App\Models\User $user) {
return $user->email;
});
// Key custom
Route::get('/posts/{post:slug}', function
Cara mengorganisir logic aplikasi dalam controller classes.
Cara membuat controller menggunakan artisan commands.
# Basic controller
php artisan make:controller UserController
# Resource controller
php artisan make:controller UserController --resource
# API resource controller
php artisan make:controller UserController --apinamespace App\Http\Controllers;
use App\Models\User;
use Illuminate\Http\Request;
class UserController extends Controller
{
public function index()
{
$users = User::
// 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()use Illuminate\Http\Request;
Route::post('/users', function (Request $request) {
// Get single value
$name = $request->input('name');
// With default
<!-- In forms -->
<form method="POST" action="/users">
@csrf
<!-- form fields -->
</form>// Exclude routes from CSRF (in app/Http/Middleware/VerifyCsrfToken.php)
protected $except = [
'stripe/*',
'webhook/*',
];Route::post('/upload', function (Request $request) {
// Cek apakah file ada
if ($request->hasFile('photo')) {
$file = $request->file(
Route::post('/users', function (Request $request) {
$validated = $request->validate([
'name' => 'required|max:255',
'email' => 'required|email|unique:users',
'password'
// Field wajib
'name' => 'required'
// Email
'email' => 'email'
// Unique di database
'email' => 'unique:users,email'
// Min/Max
'password' => 'min:8|max:20'
'age'
$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.',
@if ($errors->any())
<div class="alert alert-danger">
<ul>
@foreach ($errors->all() as $error)
<li>{{ $error }}</li>
@endforeach
</ul>
</div>
@endif
// Return view
return view('welcome');
// With data
return view('users.profile', ['name' => 'John']);
// Or use compact
$name = 'John';
return view('users.profile'
<!-- Variables -->
<h1>Hello, {{ $name }}</h1>
<!-- Unescaped (hati-hati XSS!) -->
{!! $html !!}
<!-- Comments -->
{{-- This is a comment --}}
<!-- Conditionals -->
@if ($user->isAdmin())
<p>Admin user</p>
<!-- Foreach -->
@foreach ($users as $user)
<p>{{ $user->name }}</p>
@endforeach
<!-- For -->
@for ($i = 0; $i < 10; $i++)
<p>Number {{ $i }}</p>
@endfor
<!-- resources/views/layouts/app.blade.php -->
<!DOCTYPE html>
<html>
<head>
<title>@yield('title', 'Default Title')</title>
</head>
<body>
@yield('content')
<!-- Include subview -->
@include('partials.header')
<!-- With data -->
@include('partials.user-card', ['user' => $user])# 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
# 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
use App\Models\User;
// Get all
$users = User::all();
// Find by ID
$user = User::find(1
// Create
$user = User::create([
'name' => 'John Doe',
'email' => 'john@example.com',
'password' => bcrypt('password'),
]);
// Find and update
// Hapus lewat model
$user = User::find(1);
$user->delete();
// Hapus lewat query
User::where('active', 0)->delete();
// Destroy pake ID
User
// One to One
class User extends Model
{
public function phone()
{
return $this->hasOne(Phone::class);
}
}
// One to Many
// Via request
$request->session()->put('key', 'value');
// Via helper
session(['key' => 'value']);
// Flash data (cuma satu request)
$request->session()->flash(// Via request
$value = $request->session()->get('key');
$value = $request->session()->get('key', 'default');
// Via helper
$value =
// Cek apakah ada
if ($request->session()->has('key')) {
//
}
// Hapus
$request->session()->forget('key');
$request->session()
use Illuminate\Support\Facades\Log;
// Log levels
Log::emergency($message);
Log::alert($message);
Log::critical($message);
Log::error($message);
Log::warning($message);
# 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
# 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# Set to production
APP_ENV=production
APP_DEBUG=false
# Generate app key (kalo belum)
php artisan key:generate