ការណែនាំ Laravel
1 / 18
មេរៀនទី ១

ការណែនាំ Laravel Framework

ស្វែងយល់ពី Laravel PHP Framework ដ៏ល្បីល្បាញ ដែលត្រូវបានប្រើប្រាស់ដោយ Developer ជាច្រើននៅទូទាំងពិភពលោក

ចំណេះដឹងថ្មី PHP ចាំបាច់
🚀 Laravel គឺជាអ្វី?
Laravel គឺជា PHP Web Framework ដ៏ពេញនិយមបំផុតមួយ ដែលត្រូវបានបង្កើតឡើងដោយ Taylor Otwell ក្នុងឆ្នាំ ២០១១ ដោយផ្អែកលើគំរូ MVC (Model-View-Controller)

លក្ខណៈពិសេសសំខាន់ៗ

Eloquent ORM
ការគ្រប់គ្រង Database ដោយស្រួល ដោយប្រើ Object-Relational Mapping
🛡️
Security
ការការពារ CSRF, XSS, SQL Injection ត្រូវបានដាក់BuiltIn
🎨
Blade Template
Template Engine ដ៏ខ្លាំងដែលអាចប្រើ PHP Code បានយ៉ាងងាយ
📦
Composer
Package Manager ដ៏ល្អសម្រាប់ PHP Dependencies
🔄
Queue System
ដំណើរការ Task ធំៗនៅ Background ដោយស្រួល
🧪
Testing
មានការ Support PHPUnit និង Feature Testing Built-in

របៀបដំណើរការ MVC

Laravel ប្រើប្រាស់ Architecture MVC ដែលជួយបំបែកកូដឱ្យមានភាពរៀបចំ ងាយស្រួលគ្រប់គ្រង

🎮
Controller
ទទួល Request រៀបចំ Logic
🗄️
Model
ទំនាក់ទំនងជាមួយ Database
👁️
View
បង្ហាញ HTML ដល់ User

ហេតុអ្វីត្រូវប្រើ Laravel?

✅ អត្ថប្រយោជន៍
  • មាន Community ធំ ងាយរក Package ជំនួយ
  • Documentation ល្អ ងាយសិក្សា
  • Artisan CLI ជួយសន្សំពេលវេលា
  • Scalable សម្រាប់ Project តូចដល់ធំ
  • Security ខ្ពស់ ការពារ Built-in
មេរៀនទី ២

ការដំឡើង Laravel

ជំហានតាំងពីការដំឡើង PHP, Composer រហូតដល់ការបង្កើត Laravel Project ថ្មី

តម្រូវការ System

SoftwareVersionភ្នំ
PHP>= 8.1php -v
Composer>= 2.0composer -V
Node.js>= 16node -v
MySQL / PostgreSQL>= 5.7 / 13Database Server

ជំហានដំឡើង

1
ដំឡើង Composer
ទាញយក Composer ពី getcomposer.org ហើយ Install
2
បង្កើត Laravel Project ថ្មី
ប្រើ Composer ឬ Laravel Installer ដើម្បីបង្កើត Project
3
Setup Database
កំណត់ Database ក្នុង .env file
4
Run Development Server
ប្រើ Artisan ដើម្បីចាក់ Server
Terminal bash
# ១. ដំឡើង Laravel Installer
composer global require laravel/installer

# ២. បង្កើត Project ថ្មី
laravel new my-project

# ឬប្រើ Composer
composer create-project laravel/laravel my-project

# ៣. ចូលទៅ Project folder
cd my-project

# ៤. ចាក់ Development Server
php artisan serve

# Server នឹង Run នៅ http://127.0.0.1:8000

ការកំណត់ .env File

ENV .env
APP_NAME=Laravel
APP_ENV=local
APP_KEY=base64:...
APP_DEBUG=true
APP_URL=http://localhost

# Database Configuration
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=my_database
DB_USERNAME=root
DB_PASSWORD=secret
💡 Artisan Commands ដ៏有用
php artisan key:generate — បង្កើត App Key
php artisan migrate — Run Database Migrations
php artisan make:model Post -mc — បង្កើត Model + Migration + Controller
php artisan route:list — មើល Routes ទាំងអស់
មេរៀនទី ៣

រចនាសម្ព័ន្ធ Project

ស្វែងយល់ពី Folder Structure របស់ Laravel និងតួនាទីរបស់ Folder/File នីមួយៗ

📁 my-project/
📁 app/ ← Core application code
📁 Http/Controllers/ ← Controllers
📁 Http/Middleware/ ← Middleware
📁 Models/ ← Eloquent Models
📁 bootstrap/ ← Framework bootstrapping
📁 config/ ← Configuration files
📁 database/ ← Migrations, Seeders, Factories
📁 public/ ← Web root (CSS, JS, Images)
📁 resources/ ← Views, Raw CSS/JS
📁 views/ ← Blade templates
📁 routes/ ← Route definitions
📄 web.php ← Web routes
📄 api.php ← API routes
📁 storage/ ← Logs, Cache, Uploads
📁 tests/ ← Unit & Feature tests
📄 .env ← Environment config
📄 composer.json ← PHP dependencies
មេរៀនទី ៤

Routing

ការកំណត់ URL Path ដែលទំនាក់ទំនងជាមួយ Function ឬ Controller ជាក់លាក់

Route ជាមូលដ្ឋាន

PHP routes/web.php
use Illuminate\Support\Facades\Route;

// ១. GET Route ធម្មតា
Route::get('/', function() {
    return view('welcome');
});

// ២. Route ជាមួយ Parameter
Route::get('/users/{id}', function($id) {
    return 'User ID: ' . $id;
});

// ៣. Route ទៅ Controller
Route::get('/posts', [PostController::class, 'index']);

// ៤. Named Route
Route::get('/profile', [UserController::class, 'profile'])->name('profile');

// ៥. Route Group ជាមួយ Prefix
Route::prefix('admin')->group(function() {
    Route::get('/dashboard', [AdminController::class, 'dashboard']);
    Route::get('/users', [AdminController::class, 'users']);
});

// ៦. Resource Route (CRUD)  
Route::resource('posts', PostController::class);

HTTP Methods

Methodការប្រើប្រាស់ឧទាហរណ៍
GETទទួលយក Dataមើល posts list
POSTបង្កើត Data ថ្មីSubmit form
PUT/PATCHUpdate Dataកែប្រែ post
DELETEលុប Dataលុប post
មេរៀនទី ៥

Controller

Controller ជួយរៀបចំ Logic ពី Route ហើយភ្ជាប់ Model ជាមួយ View

បង្កើត Controller

Terminalbash
# បង្កើត Controller ធម្មតា
php artisan make:controller PostController

# បង្កើត Resource Controller (CRUD Methods)
php artisan make:controller PostController --resource
PHPapp/Http/Controllers/PostController.php
namespace App\Http\Controllers;

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

class PostController extends Controller
{
    // បង្ហាញ Posts ទាំងអស់
    public function index()
    {
        $posts = Post::latest()->paginate(10);
        return view('posts.index', compact('posts'));
    }

    // Form បង្កើត Post ថ្មី
    public function create()
    {
        return view('posts.create');
    }

    // Save Post ថ្មីចូល Database
    public function store(Request $request)
    {
        $validated = $request->validate([
            'title'   => 'required|max:255',
            'content' => 'required',
        ]);

        Post::create($validated);

        return redirect()->route('posts.index')
                        ->with('success', 'Post created!');
    }

    // មើល Post ជាក់លាក់
    public function show(Post $post)
    {
        return view('posts.show', compact('post'));
    }

    // លុប Post
    public function destroy(Post $post)
    {
        $post->delete();
        return back()->with('success', 'Post deleted!');
    }
}
មេរៀនទី ៦

Blade Template Engine

Blade គឺជា Template Engine ដ៏ខ្លាំងរបស់ Laravel ដែលអនុញ្ញាតឱ្យប្រើ PHP ក្នុង HTML បានស្រួល

Blade Syntax មូលដ្ឋាន

Bladeresources/views/posts/index.blade.php
{{-- Layout Extension --}}
@@extends('layouts.app')

@@section('title', 'Posts')

@@section('content')

    {{-- Variables --}}
    <h1>{{ $title }}</h1>

    {{-- If/Else --}}
    @@if(count($posts) > 0)
        {{-- Foreach Loop --}}
        @foreach($posts as $post)
            <div class="card">
                <h2>{{ $post->title }}</h2>
                <p>{{ Str::limit($post->content, 150) }}</p>
                <a href="{{ route('posts.show', $post) }}">អានបន្ថែម</a>
            </div>
        @@endforeach

        {{-- Pagination --}}
        {{ $posts->links() }}
    @@else
        <p>មិនមាន Post ទេ!</p>
    @@endif

@@endsection

Layout File

Bladeresources/views/layouts/app.blade.php
<!DOCTYPE html>
<html>
<head>
    <title>@@yield('title', 'MyApp')</title>
</head>
<body>
    @@include('partials.navbar')

    <main>
        @@yield('content')
    </main>
</body>
</html>
មេរៀនទី ៧

Migration & Database

Migration អនុញ្ញាតឱ្យ Manage Database Schema ដោយប្រើ PHP Code ជំនួស SQL

Terminalbash
# បង្កើត Migration
php artisan make:migration create_posts_table

# Run Migration
php artisan migrate

# Rollback
php artisan migrate:rollback
PHPdatabase/migrations/..._create_posts_table.php
public function up(): void
{
    Schema::create('posts', function(Blueprint $table) {
        $table->id();                         // id auto-increment
        $table->foreignId('user_id')->constrained();
        $table->string('title');               // VARCHAR(255)
        $table->text('content');               // TEXT
        $table->string('image')->nullable();    // Nullable
        $table->boolean('is_published')->default(false);
        $table->timestamps();                  // created_at, updated_at
    });
}
មេរៀនទី ៨

Eloquent ORM

Eloquent ORM ជា Database Layer ដ៏ខ្លាំងរបស់ Laravel ដែលអនុញ្ញាតឱ្យ Query Database ដោយប្រើ PHP Objects

PHPapp/Models/Post.php
class Post extends Model
{
    // Fields ដែលអាច Fill បាន
    protected $fillable = ['title', 'content', 'user_id'];

    // Relationship: Post belongs to User
    public function user() {
        return $this->belongsTo(User::class);
    }

    // Relationship: Post has many Comments
    public function comments() {
        return $this->hasMany(Comment::class);
    }
}

Eloquent Queries

PHPController
// ទទួលទាំងអស់
$posts = Post::all();

// រកតាម ID
$post = Post::find(1);

// Filter & Paginate
$posts = Post::where('is_published', true)
              ->orderBy('created_at', 'desc')
              ->paginate(10);

// Eager Loading (N+1 Fix)
$posts = Post::with(['user', 'comments'])->get();

// Create
Post::create([
    'title'   => 'ចំណងជើងថ្មី',
    'content' => 'Content...',
    'user_id' => auth()->id(),
]);

// Update
$post->update(['title' => 'ចំណងជើងថ្មី']);

// Delete
$post->delete();
មេរៀនទី ៩

Middleware

Middleware ដំណើរការនៅ Between Request & Response ។ ប្រើសម្រាប់ Authentication, Logging, Rate Limiting...

Terminalbash
php artisan make:middleware CheckAdmin
PHPapp/Http/Middleware/CheckAdmin.php
public function handle(Request $request, Closure $next): Response
{
    // ពិនិត្យថា User ជា Admin ឬទេ
    if (!auth()->check() || !auth()->user()->isAdmin()) {
        return redirect('/')->with('error', 'Unauthorized!');
    }

    return $next($request);
}
PHProutes/web.php - ប្រើ Middleware
// ប្រើ Middleware ជាមួយ Route Group
Route::middleware(['auth', 'check.admin'])->group(function() {
    Route::get('/admin/dashboard', [AdminController::class, 'index']);
});
មេរៀនទី ១០

Form Validation

Laravel Validation ជួយ Validate Data ដែលបានផ្ញើពី Form មុននឹង Save ចូល Database

PHPController - Inline Validation
public function store(Request $request)
{
    $request->validate([
        'name'     => 'required|string|max:255',
        'email'    => 'required|email|unique:users,email',
        'password' => 'required|min:8|confirmed',
        'age'      => 'nullable|integer|min:18',
        'photo'    => 'nullable|image|max:2048',
    ], [
        // Custom Error Messages ជាភាសាខ្មែរ
        'name.required'     => 'សូមបញ្ចូលឈ្មោះ!',
        'email.required'    => 'សូមបញ្ចូល Email!',
        'email.unique'      => 'Email នេះត្រូវបានប្រើប្រាស់រួចហើយ!',
        'password.min'      => 'Password ត្រូវមានយ៉ាងតិច ៨ តួ!',
    ]);

    // If valid, save to DB
    User::create($request->validated());
}
Bladeបង្ហាញ Error Messages
<input type="text" name="name" value="{{ old('name') }}">

@@error('name')
    <span class="error">{{ $message }}</span>
@@enderror
មេរៀនទី ១១

Authentication

Laravel Breeze / Sanctum / Passport សម្រាប់ Authentication System

Terminalដំឡើង Laravel Breeze
# ១. ដំឡើង Breeze Package
composer require laravel/breeze --dev

# ២. Install Breeze
php artisan breeze:install blade

# ៣. Run Migrations
php artisan migrate

# ៤. Build Assets
npm install && npm run dev

Manual Authentication

PHPAuthController.php
use Illuminate\Support\Facades\Auth;

// Login
public function login(Request $request)
{
    $credentials = $request->only('email', 'password');

    if (Auth::attempt($credentials)) {
        $request->session()->regenerate();
        return redirect()->intended('/dashboard');
    }

    return back()->withErrors([
        'email' => 'Email ឬ Password មិនត្រឹមត្រូវ!',
    ]);
}

// Logout
public function logout(Request $request)
{
    Auth::logout();
    $request->session()->invalidate();
    return redirect('/');
}

// ពិនិត្យ User ក្នុង View
// @auth ... @endauth
// auth()->user()->name
មេរៀនទី ១២

File Upload

ការ Upload រូបភាព ឬ File ក្នុង Laravel ដោយប្រើ Storage Facade

PHPController - Handle Upload
use Illuminate\Support\Facades\Storage;

public function store(Request $request)
{
    $request->validate([
        'image' => 'required|image|mimes:jpeg,png,jpg|max:2048'
    ]);

    // ១. Save ទៅ storage/app/public/images
    if ($request->hasFile('image')) {
        $path = $request->file('image')->store('images', 'public');

        // $path = 'images/randomname.jpg'
        Post::create([
            'title' => $request->title,
            'image' => $path,
        ]);
    }
}

// បង្ហាញ Image ក្នុង Blade
// <img src="{{ Storage::url($post->image) }}">

// ២. Link Storage Folder (run once)
// php artisan storage:link
មេរៀនទី ១៣

API Development

ការបង្កើត RESTful API ជាមួយ Laravel Sanctum Authentication

Intermediate
PHProutes/api.php
use Illuminate\Support\Facades\Route;

// Public Routes
Route::post('/login', [AuthController::class, 'login']);
Route::post('/register', [AuthController::class, 'register']);

// Protected Routes (require token)
Route::middleware('auth:sanctum')->group(function() {
    Route::get('/user', function(Request $req) {
        return $req->user();
    });

    Route::apiResource('posts', PostController::class);
    Route::post('/logout', [AuthController::class, 'logout']);
});
PHPAPI Resource - JSON Response
// app/Http/Resources/PostResource.php
class PostResource extends JsonResource
{
    public function toArray(Request $request): array
    {
        return [
            'id'         => $this->id,
            'title'      => $this->title,
            'content'    => $this->content,
            'author'     => $this->user->name,
            'created_at' => $this->created_at->format('d/m/Y'),
        ];
    }
}

// ប្រើក្នុង Controller
return PostResource::collection(Post::paginate(10));
មេរៀនទី ១៤

Queue & Jobs

ដំណើរការ Task ធំៗ ដូចជា Email, Notification, Processing Files នៅ Background

Advanced
Terminalbash
# បង្កើត Job
php artisan make:job SendWelcomeEmail

# Run Queue Worker
php artisan queue:work
PHPapp/Jobs/SendWelcomeEmail.php
class SendWelcomeEmail implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    public function __construct(
        public readonly User $user
    ) {}

    public function handle(): void
    {
        Mail::to($this->user)->send(new WelcomeMail($this->user));
    }
}

// Dispatch Job (ក្នុង Controller)
SendWelcomeEmail::dispatch($user);

// Delay 5 minutes
SendWelcomeEmail::dispatch($user)->delay(now()->addMinutes(5));
មេរៀនទី ១៥

Events & Listeners

Event-Driven Architecture ក្នុង Laravel ជួយបំបែក Business Logic ឱ្យ Decoupled

Terminalbash
php artisan make:event UserRegistered
php artisan make:listener SendWelcomeNotification --event=UserRegistered
PHPEvent & Listener
// Event Class
class UserRegistered
{
    public function __construct(public User $user) {}
}

// Listener Class
class SendWelcomeNotification
{
    public function handle(UserRegistered $event): void
    {
        $event->user->notify(new WelcomeNotification());
    }
}

// Fire Event
event(new UserRegistered($user));
មេរៀនទី ១៦

Caching

ការប្រើ Cache ដើម្បីបង្កើន Performance ដោយ Store Results ណែ Database / API Queries

PHPCache Usage
use Illuminate\Support\Facades\Cache;

// ១. Store value ២ ម៉ោង
Cache::put('key', 'value', now()->addHours(2));

// ២. Get value
$value = Cache::get('key', 'default');

// ៣. Remember (Store if not exists)
$posts = Cache::remember('all_posts', 3600, function() {
    return Post::with('user')->get();
});

// ៤. Delete cache
Cache::forget('all_posts');

// ៥. Clear all cache
Cache::flush();
ℹ️ Cache Drivers
Laravel Support: File (default), Database, Redis, Memcached
Redis ផ្តល់នូវ Performance ខ្ពស់បំផុតសម្រាប់ Production
មេរៀនទី ១៧

Testing

Laravel ភ្ជាប់ PHPUnit Built-in ។ Feature Tests ជួយ Test HTTP Requests, Database, Authentication

PHPtests/Feature/PostTest.php
class PostTest extends TestCase
{
    use RefreshDatabase;

    public function test_user_can_view_posts(): void
    {
        // Create test data
        $user  = User::factory()->create();
        $posts = Post::factory(5)->create(['user_id' => $user->id]);

        // Make request as logged-in user
        $response = $this->actingAs($user)->get('/posts');

        // Assert response
        $response->assertStatus(200);
        $response->assertViewHas('posts');
    }

    public function test_user_can_create_post(): void
    {
        $user = User::factory()->create();

        $response = $this->actingAs($user)->post('/posts', [
            'title'   => 'Test Post',
            'content' => 'Test Content...',
        ]);

        $response->assertRedirect('/posts');
        $this->assertDatabaseHas('posts', ['title' => 'Test Post']);
    }
}
TerminalRun Tests
# Run all tests
php artisan test

# Run specific test file
php artisan test tests/Feature/PostTest.php

# Run with coverage
php artisan test --coverage
មេរៀនទី ១៨

Deployment ទៅ Production

ការ Deploy Laravel Application ទៅ Server ផ្ទាល់ ឬ Cloud Platform

Advanced

Production Checklist

⚠️ ត្រូវធ្វើមុន Deploy
  • ដាក់ APP_DEBUG=false ក្នុង .env
  • ដាក់ APP_ENV=production
  • Generate APP_KEY ថ្មី
  • Setup Database SSL
  • Configure Mail, Queue, Cache drivers
TerminalDeployment Commands
# ១. Pull Code ពី Git
git pull origin main

# ២. Install Dependencies
composer install --no-dev --optimize-autoloader

# ៣. Run Migrations
php artisan migrate --force

# ៤. Cache Configuration (Speed up)
php artisan config:cache
php artisan route:cache
php artisan view:cache

# ៥. Build Assets
npm install && npm run build

# ៦. Clear Old Cache
php artisan cache:clear

# ៧. Set Permissions
chmod -R 775 storage bootstrap/cache
🎉 សូមអបអរ!
អ្នកបានបញ្ចប់មេរៀន Laravel Framework ពេញលេញហើយ! ចំណេះដឹងទាំងនេះគ្របដណ្តប់ស្ទើរបទពិសោធន៍ Developer ពីថ្នាក់ Beginner ដល់ Advanced ។ ជំហានបន្ទាប់ — សាកល្បងបង្កើត Project ពិតប្រាកដ!

ធនធានបន្ថែម

ធនធានURL
Official Docslaravel.com/docs
Laracasts (Video)laracasts.com
Laravel Newslaravel-news.com
Packagistpackagist.org