
Học Laravel 10 cơ bản: CRUD cơ bản trong Laravel 10
Trong bài viết này, bạn sẽ học cách xây dựng CRUD cơ bản trong Laravel 10 để quản lý dữ liệu posts một cách trực quan.
👉Mục tiêu: Làm tính năng CRUD (Create – Read – Update – Delete) cho bảng posts
.
1. Chuẩn bị Migration + Model trong Laravel 10
Tạo migration + model:
php artisan make:model Post -m
File migration: database/migrations/xxxx_create_posts_table.php
public function up(): void { Schema::create('posts', function (Blueprint $table) { $table->id(); $table->string('title'); $table->text('content')->nullable(); $table->string('image')->nullable(); // lưu tên file ảnh $table->timestamps(); }); }
Chạy migration:
php artisan migrate
Model app/Models/Post.php
:
2. Tạo Controller Resource cho CRUD Laravel
php artisan make:controller PostController --resource
Laravel tạo app/Http/Controllers/PostController.php
với sẵn 7 action:
-
index, create, store, show, edit, update, destroy.
3. Định nghĩa Route CRUD trong Laravel
Trong routes/web.php
:
👉 Laravel sẽ tạo sẵn route CRUD:
-
GET
/posts
→ index -
GET
/posts/create
→ create -
POST
/posts
→ store -
GET
/posts/{id}
→ show -
GET
/posts/{id}/edit
→ edit -
PUT/PATCH
/posts/{id}
→ update -
DELETE
/posts/{id}
→ destroy
4. Code Controller CRUD Laravel 10
app/Http/Controllers/PostController.php
:
5. Tạo View Blade cho CRUD Laravel
Thư mục: resources/views/posts/
index.blade.php
create.blade.php
edit.blade.php
@extends('layouts.app') @section('content') <h2>Sửa bài viết</h2> @if ($errors->any()) <ul style="color:red"> @foreach ($errors->all() as $error) <li>{{ $error }}</li> @endforeach </ul> @endif <form action="{{ route('posts.update', $post) }}" method="POST" enctype="multipart/form-data"> @csrf @method('PUT') <label>Tiêu đề:</label><br> <input type="text" name="title" value="{{ old('title', $post->title) }}"><br><br> <label>Nội dung:</label><br> <textarea name="content">{{ old('content', $post->content) }}</textarea><br><br> <label>Ảnh:</label><br> @if($post->image) <img src="{{%20asset('storage/'%20.%20$post->image)%20}}" width="80"><br> @endif <input type="file" name="image"><br><br> <button type="submit">Cập nhật</button> </form> @endsection
show.blade.php
@extends('layouts.app') @section('content') <h2>{{ $post->title }}</h2> <p>{{ $post->content }}</p> @if($post->image) <img src="{{%20asset('storage/'%20.%20$post->image)%20}}" width="200"> @endif <br><a href="{{%20route('posts.index')%20}}">← Quay lại</a> @endsection
6. Layout chung để CRUD trong Laravel
Tạo file resources/views/layouts/app.blade.php
:
✅ Kết quả
Bạn đã có CRUD cơ bản hoàn chỉnh cho bảng posts
:
-
Xem danh sách
-
Thêm mới
-
Sửa
-
Xóa
-
Upload ảnh