Tạo bởi Trần Văn Điêp|
Học Laravel

[Video] Bài tập quản lý sách bằng Laravel - Full Source Code quản lý sách - Lập trình Laravel

Source Code - Quản lý sách



Mở bài

Bài tập quản lý sách bằng Laravel là một đề tài thực hành tuyệt vời cho những ai muốn làm chủ framework PHP phổ biến này. Thay vì học lý thuyết suông, làm một dự án nhỏ như quản lý thư viện giúp bạn tiếp xúc trực tiếp với các khái niệm quan trọng: route, controller, model, migration, seeder, Blade templates, Eloquent ORM, validation, file upload, pagination và nhiều kỹ thuật khác. Dự án này vừa đủ đơn giản để hoàn thành trong thời gian ngắn, vừa đủ thực tiễn để đem vào portfolio khi xin việc.

Trong bài viết này mình sẽ hướng dẫn Bài tập quản lý sách bằng Laravel từ đầu đến cuối — trình bày kiến trúc, tạo cơ sở dữ liệu, viết migration, seed dữ liệu, xây model, controller, route, view và một số tính năng mở rộng như tìm kiếm, phân trang, upload ảnh bìa. Mình cũng sẽ chia sẻ best practices, mẹo debug và cách đóng gói full source code để bạn có thể dễ dàng nhân rộng và triển khai. Nếu bạn đang trong khóa học Laravel hoặc tự học, bài tập này là lựa chọn hoàn hảo để thực hành.


Tổng quan dự án: yêu cầu chức năng và kiến trúc

Trước khi bắt tay code, cần xác định yêu cầu rõ ràng cho Bài tập quản lý sách bằng Laravel:

  • Quản lý sách (CRUD): Thêm, Sửa, Xóa, Danh sách.

  • Mỗi sách có: tiêu đề, tác giả, mô tả ngắn, thể loại, năm xuất bản, số trang và ảnh bìa.

  • Tìm kiếm sách theo tiêu đề/tác giả/thể loại.

  • Phân trang danh sách sách.

  • Upload ảnh bìa và lưu trữ an toàn.

  • Validation form, hiển thị thông báo lỗi.

  • (Tùy chọn) API trả JSON cho danh sách sách.

Kiến trúc đề xuất:

  • Routes: routes/web.php

  • Controller: app/Http/Controllers/BookController.php

  • Model: app/Models/Book.php

  • Migration/Seeder cho bảng books

  • Views: resources/views/books/*.blade.php

  • Storage: storage/app/public/covers + php artisan storage:link

Với cấu trúc này, bạn có thể mở rộng chức năng (thêm authentication, role, export/import CSV) mà không phá vỡ nền tảng.


Bắt đầu: khởi tạo dự án và cấu hình môi trường

Để thực hiện Bài tập quản lý sách bằng Laravel, trước hết cần tạo project:

  1. Cài Laravel (via Composer):

composer create-project laravel/laravel book-manager cd book-manager
  1. Cấu hình .env kết nối MySQL:

DB_DATABASE=bookdb DB_USERNAME=root DB_PASSWORD=secret
  1. Tạo symbolic link cho storage (dùng để public ảnh bìa):

php artisan storage:link
  1. Chạy server:

php artisan serve

Sau khi thiết lập, ta sang bước tạo migration và model. Việc chuẩn bị môi trường kỹ càng giúp dự án Bài tập quản lý sách bằng Laravel chạy mượt trên máy local.


Migration và Seeder: tạo cấu trúc bảng và dữ liệu mẫu

Migration tạo bảng books:

php artisan make:migration create_books_table --create=books

Trong file migration:

Schema::create('books', function (Blueprint $table) { $table->id(); $table->string('title'); $table->string('author')->nullable(); $table->string('genre')->nullable(); $table->text('description')->nullable(); $table->integer('year')->nullable(); $table->integer('pages')->nullable(); $table->string('cover')->nullable(); // path to cover image $table->timestamps(); });

Chạy migrate:

php artisan migrate

Tạo seeder để fake dữ liệu:

php artisan make:seeder BookSeeder

Trong BookSeeder dùng Faker hoặc Factory:

public function run() { \App\Models\Book::factory(50)->create(); }

Tạo factory:

php artisan make:factory BookFactory --model=Book

Trong factory:

return [ 'title' => $this->faker->sentence(3), 'author' => $this->faker->name, 'genre' => $this->faker->randomElement(['Fiction','Science','History','Programming']), 'description' => $this->faker->paragraph, 'year' => $this->faker->year, 'pages' => $this->faker->numberBetween(50, 1000), ];

Seed DB:

php artisan db:seed --class=BookSeeder

Việc chuẩn bị dữ liệu mẫu giúp bạn thử nghiệm nhanh các tính năng hiển thị, tìm kiếm và phân trang trong Bài tập quản lý sách bằng Laravel.


Model & Eloquent: định nghĩa Book và scope tìm kiếm

Tạo model:

php artisan make:model Book

Trong app/Models/Book.php:

class Book extends Model { protected $fillable = ['title','author','genre','description','year','pages','cover']; // scope search để tái sử dụng public function scopeSearch($query, $term) { if (empty($term)) return $query; $term = "%$term%"; return $query->where('title', 'like', $term) ->orWhere('author', 'like', $term) ->orWhere('genre', 'like', $term); } }

Dùng scope giúp controller ngắn gọn, và tăng tính tái sử dụng khi xử lý truy vấn phức tạp.


Routes: định tuyến CRUD và search

Trong routes/web.php thêm:

use App\Http\Controllers\BookController; Route::get('/', [BookController::class,'index'])->name('books.index'); Route::get('/books/create', [BookController::class,'create'])->name('books.create'); Route::post('/books', [BookController::class,'store'])->name('books.store'); Route::get('/books/{book}/edit', [BookController::class,'edit'])->name('books.edit'); Route::put('/books/{book}', [BookController::class,'update'])->name('books.update'); Route::delete('/books/{book}', [BookController::class,'destroy'])->name('books.destroy'); Route::get('/books/{book}', [BookController::class,'show'])->name('books.show');

Bạn cũng có thể dùng Route::resource('books', BookController::class) để tạo nhanh toàn bộ route CRUD. Việc phân bổ route rõ ràng giúp SEO và RESTful API chuẩn hơn.


Controller: logic xử lý CRUD, upload cover và paginate

Tạo controller:

php artisan make:controller BookController --resource

Các method chính:

index()

  • Nhận query search

  • Lấy danh sách sách: Book::search($q)->orderBy('created_at','desc')->paginate(10)->withQueryString();

  • Trả view books.index

create() & store()

  • Hiển thị form books.create

  • Validate dữ liệu:

$request->validate([ 'title' => 'required|string|max:255', 'author' => 'nullable|string|max:255', 'cover' => 'nullable|image|max:2048', ]);
  • Lưu cover nếu có:

if ($request->hasFile('cover')) { $path = $request->file('cover')->store('covers','public'); $data['cover'] = $path; } Book::create($data);

edit() & update()

  • Tương tự store, replace cover cũ nếu upload mới (xóa file cũ via Storage::delete).

destroy()

  • Xoá bản ghi và ảnh bìa tương ứng.

Chú ý: luôn dùng transactions nếu thao tác nhiều bảng cùng lúc.


Views: Blade templates cho danh sách và form

Tổ chức view:

resources/views/layouts/app.blade.php resources/views/books/index.blade.php resources/views/books/create.blade.php resources/views/books/edit.blade.php resources/views/books/show.blade.php

Layout chung layouts/app.blade.php chứa header/menu, link CSS/JS, và @yield('content').

books/index.blade.php:

  • Form search (GET)

  • Table hiển thị danh sách: title, author, genre, year, cover (thumbnail)

  • Buttons edit/delete

  • Pagination: {{ $books->links() }}

books/create.blade.php:

  • form method POST, enctype="multipart/form-data", @csrf

  • fields: title, author, genre, year, pages, cover

  • show validation errors with @error

Việc thiết kế UI thân thiện giúp trải nghiệm quản lý sách trong Bài tập quản lý sách bằng Laravel chuyên nghiệp hơn.


Tìm kiếm, phân trang và tối ưu truy vấn

  • Dùng paginate(10) thay vì get() để tránh lấy quá nhiều bản ghi.

  • Sử dụng withQueryString() để giữ tham số tìm kiếm khi chuyển trang.

  • Index cột database (title, author) giúp tăng tốc LIKE queries.

  • Cache kết quả tìm kiếm phổ biến bằng Redis nếu cần.

Ví dụ trong controller:

$books = Book::search($q)->orderBy('title')->paginate(10)->withQueryString();

Những bước này đảm bảo ứng dụng vẫn mượt khi dataset lớn, qua đó bài tập quản lý sách bằng Laravel có thể mở rộng lên production.


Validation, bảo mật và xử lý file

  • Luôn validate request dùng FormRequest nếu logic lớn:

php artisan make:request StoreBookRequest
  • Dùng Storage::disk('public')->putFile() để lưu file an toàn.

  • Hạn chế kích thước file, kiểm tra mime-type.

  • Escape output ({{ }}) trong Blade để tránh XSS.

  • Dùng CSRF token (@csrf) cho form.

Bảo mật là yếu tố không thể bỏ qua khi chia sẻ source code quản lý sách cho người dùng thực tế.


Testing và debug

  • Viết Feature Tests cho CRUD:

php artisan make:test BookTest
  • Test nhập liệu hợp lệ, redirect, database has.

  • Dùng php artisan migrate:fresh --seed để reset DB khi test.

  • Debug với dd() hoặc Log::debug(). Xem logs ở storage/logs/laravel.log.

Testing giúp bạn yên tâm refactor mà không phá vỡ chức năng.


Triển khai & full source code

Khi hoàn chỉnh, bạn có thể đóng gói full source code:

  • Push lên GitHub (kèm .env.example, README hướng dẫn cài đặt).

  • Tạo script seed dữ liệu demo.

  • Hướng dẫn setup: composer install, cp .env.example .env, php artisan key:generate, php artisan migrate --seed, php artisan storage:link.

Triển khai lên server dùng Forge, DigitalOcean hoặc shared hosting hỗ trợ PHP. Đảm bảo cấu hình APP_ENV=production, bật cache php artisan config:cache, route:cache, view:cache.


Mẹo tối ưu và lời khuyên cho người học

  1. Code nhỏ, modular: tách service layer cho logic phức tạp.

  2. Sử dụng Resource Controllers & Route Model Binding để code ngắn và an toàn.

  3. Dùng policies nếu muốn kiểm soát quyền chỉnh sửa/xoá sách.

  4. UI/UX: thêm modal confirm khi xóa, hiển thị progress khi upload ảnh lớn.

  5. Documentation: viết README rõ ràng cho full source code.

  6. Performance: luôn dùng paginate và index DB.

Những thói quen này giúp bạn nâng chất lượng bài tập quản lý sách bằng Laravel từ demo thành ứng dụng chuyên nghiệp.


Kết luận

Bài tập quản lý sách bằng Laravel là một project hoàn hảo để học và luyện tập toàn diện các kỹ năng phát triển web: từ thiết kế database, migration, seeding, tới Eloquent, routes, controllers, Blade views, validation, file upload, tìm kiếm và phân trang. Việc hoàn thiện một bản full source code quản lý sách không chỉ giúp bạn hiểu sâu Laravel mà còn tạo ra sản phẩm thực tế để trình bày trong hồ sơ xin việc.

Hãy bắt tay vào thực hiện: tạo project, viết migration, seed dữ liệu, xây model, controller và view theo hướng dẫn ở trên. Khi hoàn thành, bạn có thể mở rộng tính năng như authentication, role-based access, export/import CSV, hoặc API cho frontend SPA. Nếu bạn cần bản sample full source code để tham khảo, hãy lưu ý cấu trúc, đặt tên rõ ràng và viết README chi tiết — điều đó sẽ nâng giá trị dự án của bạn lên rất nhiều. Chúc bạn học tốt và sớm hoàn thành bài tập quản lý sách bằng Laravel thành một ứng dụng thực tế, hữu ích và chuyên nghiệp!


Phản hồi từ học viên

5

Tổng 0 đánh giá

Đăng nhập để làm bài kiểm tra

Chưa có kết quả nào trước đó