Skip to content
PHP Laravel MVC入门指南从零基础到实战项目开发的完整学习路径与最佳实践分享
什么是Laravel以及为什么选择Laravel进行MVC开发
Laravel是一个基于PHP的现代化Web开发框架,它遵循MVC(Model-View-Controller)设计模式,为开发者提供了优雅且富有表现力的语法。Laravel的核心理念是让Web开发变得更加简单、快速和可维护。根据2023年的开发者调查,Laravel连续多年被评为最受欢迎的PHP框架,这得益于其强大的生态系统、活跃的社区和丰富的功能特性。
选择Laravel进行MVC开发有以下几个关键优势:
优雅的语法
:Laravel的语法简洁直观,让常见的Web开发任务变得简单
完整的工具链
:从数据库迁移、队列处理到API开发,Laravel提供了完整的解决方案
强大的安全性
:内置CSRF保护、SQL注入防护、XSS防护等安全机制
活跃的社区
:拥有庞大的开发者社区和丰富的第三方包
完善的文档
:官方文档详细且持续更新,学习曲线平缓
开发环境搭建与Laravel安装
系统要求与环境准备
在开始Laravel开发之前,我们需要准备合适的开发环境。Laravel 10.x版本要求:
PHP >= 8.1
Composer(PHP包管理器)
数据库(MySQL、PostgreSQL、SQLite等)
推荐的开发环境选择:
Laravel Sail
:基于Docker的开发环境,包含所有必需的服务
XAMPP/MAMP
:传统的本地开发环境
Laravel Valet
:轻量级的Mac开发环境
安装Laravel的完整步骤
首先确保你的系统已安装PHP 8.1+和Composer。可以通过以下命令检查:
php -v
composer –version
使用Composer创建新的Laravel项目:
# 方法1:通过Composer创建项目(推荐)
composer create-project laravel/laravel my-app
# 方法2:使用Laravel安装器(需要先全局安装)
composer global require laravel/installer
laravel new my-app
创建完成后,进入项目目录并启动开发服务器:
cd my-app
php artisan serve
现在你可以在浏览器中访问
http://127.0.0.1:8000
看到Laravel的欢迎页面。
配置数据库连接
打开项目根目录下的
.env
文件,配置数据库连接信息:
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=my_app
DB_USERNAME=root
DB_PASSWORD=
Laravel MVC架构详解
MVC模式的核心概念
MVC(Model-View-Controller)是一种软件设计模式,将应用程序分为三个主要组件:
Model(模型)
:负责处理数据和业务逻辑,与数据库交互
View(视图)
:负责显示数据,即用户界面
Controller(控制器)
:负责接收用户输入,协调Model和View
Laravel中的路由系统
路由是Laravel中请求的入口点,负责将URL映射到相应的控制器方法。基本路由定义在
routes/web.php
文件中:
paginate(10);
return view(‘posts.index’, compact(‘posts’));
}
/**
* 显示创建文章表单
*/
public function create()
{
return view(‘posts.create’);
}
/**
* 存储新文章
*/
public function store(Request $request)
{
// 数据验证
$validated = $request->validate([
‘title’ => ‘required|string|max:255’,
‘content’ => ‘required|string’,
‘status’ => ‘in:draft,published’
]);
// 创建文章
$post = Post::create($validated + [‘user_id’ => auth()->id()]);
return redirect()->route(‘posts.show’, $post)->with(‘success’, ‘文章创建成功!’);
}
/**
* 显示单篇文章
*/
public function show(Post $post)
{
return view(‘posts.show’, compact(‘post’));
}
/**
* 显示编辑表单
*/
public function edit(Post $post)
{
$this->authorize(‘update’, $post); // 权限检查
return view(‘posts.edit’, compact(‘post’));
}
/**
* 更新文章
*/
public function update(Request $request, Post $post)
{
$this->authorize(‘update’, $post);
$validated = $request->validate([
‘title’ => ‘required|string|max:255’,
‘content’ => ‘required|string’,
‘status’ => ‘in:draft,published’
]);
$post->update($validated);
return redirect()->route(‘posts.show’, $post)->with(‘success’, ‘文章更新成功!’);
}
/**
* 删除文章
*/
public function destroy(Post $post)
{
$this->authorize(‘delete’, $post);
$post->delete();
return redirect()->route(‘posts.index’)->with(‘success’, ‘文章删除成功!’);
}
}
数据库与模型(Model)
数据库迁移
迁移是Laravel管理数据库结构的方式,使用迁移可以版本控制数据库变更。创建迁移文件:
php artisan make:migration create_posts_table
在生成的迁移文件中定义表结构:
id();
$table->foreignId(‘user_id’)->constrained()->onDelete(‘cascade’);
$table->string(‘title’);
$table->text(‘content’);
$table->enum(‘status’, [‘draft’, ‘published’])->default(‘draft’);
$table->timestamps(); // 创建created_at和updated_at字段
$table->softDeletes(); // 软删除支持
});
}
public function down()
{
Schema::dropIfExists(‘posts’);
}
};
运行迁移:
php artisan migrate
创建模型
模型位于
app/Models
目录,负责与数据库交互:
‘datetime’,
‘updated_at’ => ‘datetime’,
‘deleted_at’ => ‘datetime’,
];
/**
* 定义与User模型的关系(一对多)
*/
public function user()
{
return $this->belongsTo(User::class);
}
/**
* 定义与Comment模型的关系(一对多)
*/
public function comments()
{
return $this->hasMany(Comment::class)->orderBy(‘created_at’, ‘desc’);
}
/**
* 作用域:获取已发布的文章
*/
public function scopePublished($query)
{
return $query->where(‘status’, ‘published’);
}
/**
* 作用域:按标题搜索
*/
public function scopeSearch($query, $keyword)
{
return $query->where(‘title’, ‘like’, “%{$keyword}%”)
->orWhere(‘content’, ‘like’, “%{$keyword}%”);
}
}
数据库操作示例
// 创建记录
$post = Post::create([
‘user_id’ => 1,
‘title’ => ‘Laravel入门指南’,
‘content’ => ‘这是一篇关于Laravel的文章…’,
‘status’ => ‘published’
]);
// 查询记录
$posts = Post::where(‘status’, ‘published’)->get();
$recentPosts = Post::orderBy(‘created_at’, ‘desc’)->take(5)->get();
// 更新记录
$post->update([‘title’ => ‘更新后的标题’]);
// 删除记录
$post->delete(); // 软删除
$post->forceDelete(); // 永久删除
// 关系查询
$user = $post->user; // 获取文章作者
$comments = $post->comments; // 获取文章评论
视图(View)与Blade模板引擎
Blade模板基础
Blade是Laravel强大的模板引擎,提供了简洁的语法和模板继承功能。Blade文件以
.blade.php
为扩展名。
创建布局模板
创建
resources/views/layouts/app.blade.php
:
@yield(‘title’, ‘我的应用’)
@if (session(‘success’))
{{ session(‘success’) }}
@endif
@if (session(‘error’))
{{ session(‘error’) }}
@endif
@yield(‘content’)
© 2023 我的博客. 基于 Laravel {{ App::VERSION() }} 构建.
@stack(‘scripts’)
创建视图文件
文章列表视图 (
resources/views/posts/index.blade.php
)
@extends(‘layouts.app’)
@section(‘title’, ‘文章列表’)
@section(‘content’)
@if ($posts->isEmpty())
@else
@foreach ($posts as $post)
{{ $post->title }}
@if ($post->status === ‘draft’)
草稿
@endif
作者:{{ $post->user->name }} |
发布时间:{{ $post->created_at->diffForHumans() }}
{{ Str::limit($post->content, 100) }}
查看
@can(‘update’, $post)
编辑
@endcan
@endforeach
{{ $posts->links() }}
@endif
总文章数
{{ \App\Models\Post::count() }}
已发布
{{ \App\Models\Post::published()->count() }}
草稿
{{ \App\Models\Post::where(‘status’, ‘draft’)->count() }}
@endsection
文章创建/编辑表单视图 (
resources/views/posts/form.blade.php
)
@extends(‘layouts.app’)
@section(‘title’, $post->exists ? ‘编辑文章’ : ‘创建文章’)
@section(‘content’)
内容
@error(‘content’)
{{ $message }}
@enderror
状态
status) === ‘draft’ ? ‘selected’ : ” }}>草稿 status) === ‘published’ ? ‘selected’ : ” }}>已发布
@error(‘status’)
{{ $message }}
@enderror
{{ $post->exists ? ‘更新文章’ : ‘创建文章’ }}
取消
@endsection
Blade高级特性
组件(Components)
创建可复用的按钮组件
resources/views/components/button.blade.php
:
@props([‘variant’ => ‘primary’, ‘type’ => ‘submit’, ‘size’ => ‘md’])
@php
$classes = [
‘btn’,
‘btn-‘ . $variant,
‘btn-‘ . $size => $size !== ‘md’,
];
@endphp
merge([‘class’ => implode(‘ ‘, $classes), ‘type’ => $type]) }}>
{{ $slot }}
使用组件:
保存
删除
指令(Directives)
Blade提供了丰富的内置指令:
{{– 条件判断 –}}
@if ($user->isAdmin())
管理员
@endif
{{– 循环 –}}
@forelse ($posts as $post)
{{ $post->title }}
@empty
暂无文章
@endforelse
{{– 包含子视图 –}}
@include(‘posts.partials.card’, [‘post’ => $post])
{{– 推送内容到指定区域 –}}
@push(‘scripts’)
@endpush
表单验证与数据处理
控制器中的验证
Laravel提供了多种验证方式,最常用的是在控制器中使用
validate
方法:
validate([
‘title’ => [
‘required’,
‘string’,
‘max:255’,
‘unique:posts,title’ // 标题必须唯一
],
‘content’ => ‘required|string|min:10’,
‘status’ => ‘in:draft,published’,
‘tags’ => ‘array’,
‘tags.*’ => ‘string|max:50’
]);
// 验证通过,创建文章
$post = Post::create($validated + [‘user_id’ => auth()->id()]);
return redirect()->route(‘posts.show’, $post)->with(‘success’, ‘文章创建成功!’);
}
public function update(Request $request, Post $post)
{
// 验证时排除当前文章
$validated = $request->validate([
‘title’ => [
‘required’,
‘string’,
‘max:255’,
‘unique:posts,title,’ . $post->id // 排除当前文章
],
‘content’ => ‘required|string|min:10’,
‘status’ => ‘in:draft,published’
]);
$post->update($validated);
return redirect()->route(‘posts.show’, $post)->with(‘success’, ‘文章更新成功!’);
}
}
表单请求验证(Form Request)
对于复杂的验证逻辑,可以使用Form Request来分离验证规则:
php artisan make:request StorePostRequest
创建
app/Http/Requests/StorePostRequest.php
:
check();
}
/**
* 获取应用于请求的验证规则
*/
public function rules(): array
{
return [
‘title’ => [
‘required’,
‘string’,
‘max:255’,
Rule::unique(‘posts’)->ignore($this->route(‘post’)?->id ?? null)
],
‘content’ => ‘required|string|min:10’,
‘status’ => [‘required’, ‘in:draft,published’],
‘tags’ => ‘sometimes|array’,
‘tags.*’ => ‘string|max:50’
];
}
/**
* 自定义验证消息
*/
public function messages(): array
{
return [
‘title.required’ => ‘文章标题不能为空’,
‘title.unique’ => ‘该标题已被使用,请更换其他标题’,
‘content.min’ => ‘文章内容至少需要10个字符’,
‘status.in’ => ‘状态只能是草稿或已发布’
];
}
/**
* 准备输入数据
*/
protected function prepareForValidation(): void
{
$this->merge([
‘slug’ => $this->title ? Str::slug($this->title) : null,
]);
}
}
在控制器中使用Form Request:
validated();
$post = Post::create($validated + [‘user_id’ => auth()->id()]);
return redirect()->route(‘posts.show’, $post)->with(‘success’, ‘文章创建成功!’);
}
public function update(StorePostRequest $request, Post $post)
{
$post->update($request->validated());
return redirect()->route(‘posts.show’, $post)->with(‘success’, ‘文章更新成功!’);
}
}
手动验证与自定义验证器
use Illuminate\Support\Facades\Validator;
// 手动创建验证器
$validator = Validator::make($request->all(), [
‘title’ => ‘required|max:255’,
‘content’ => ‘required’
]);
// 自定义验证规则
$validator->sometimes(‘price’, ‘min:0’, function ($input) {
return $input->isFree === false;
});
// 验证并获取错误
if ($validator->fails()) {
return redirect()->back()
->withErrors($validator)
->withInput();
}
// 获取验证后的数据
$validated = $validator->validated();
Eloquent ORM深度使用
关系定义
Eloquent是Laravel的ORM,提供了优雅的数据库操作方式。关系定义在模型中:
belongsTo(User::class);
}
// 一对多关系(Post有多个Comment)
public function comments(): HasMany
{
return $this->hasMany(Comment::class)->orderBy(‘created_at’, ‘desc’);
}
// 多对多关系(Post有多个Tag,Tag也属于多个Post)
public function tags(): BelongsToMany
{
return $this->belongsToMany(Tag::class, ‘post_tags’);
}
// 一对一多态关系
public function image()
{
return $this->morphOne(Image::class, ‘imageable’);
}
}
查询构建器高级用法
// 基础查询
$posts = Post::where(‘status’, ‘published’)
->orderBy(‘created_at’, ‘desc’)
->with([‘user’, ‘comments.user’]) // 预加载关系,避免N+1问题
->paginate(10);
// 复杂条件查询
$posts = Post::where(function ($query) {
$query->where(‘status’, ‘published’)
->orWhere(‘user_id’, auth()->id());
})
->when(request(‘search’), function ($query, $search) {
return $query->where(‘title’, ‘like’, “%{$search}%”);
})
->withCount(‘comments’) // 添加评论数量字段
->get();
// 子查询
$posts = Post::select(‘*’)
->selectSub(
‘SELECT COUNT(*) FROM comments WHERE comments.post_id = posts.id’,
‘comments_count’
)
->get();
// 更新增量值
$post->increment(‘view_count’);
$post->decrement(‘view_count’, 5);
访问器和修改器
class Post extends Model
{
// 访问器:获取属性时自动格式化
public function getExcerptAttribute()
{
return Str::limit($this->content, 150);
}
// 修改器:设置属性时自动处理
public function setTitleAttribute($value)
{
$this->attributes[‘title’] = $value;
$this->attributes[‘slug’] = Str::slug($value);
}
// 日期访问器
public function getCreatedAtAttribute($value)
{
return Carbon::parse($value)->diffForHumans();
}
}
认证与授权
快速生成认证系统
Laravel提供了开箱即用的认证脚手架:
# 安装UI包(Laravel 9/10)
composer require laravel/ui
php artisan ui bootstrap –auth
# 或者使用Breeze(推荐,更现代化)
composer require laravel/breeze –dev
php artisan breeze:install
npm install && npm run build
自定义认证逻辑
validate([
’email’ => ‘required|email’,
‘password’ => ‘required’,
]);
if (Auth::attempt($credentials, $request->boolean(‘remember’))) {
$request->session()->regenerate();
return redirect()->intended(‘dashboard’);
}
return back()->withErrors([
’email’ => ‘提供的凭据与我们的记录不符。’,
])->onlyInput(’email’);
}
public function logout(Request $request)
{
Auth::guard(‘web’)->logout();
$request->session()->invalidate();
$request->session()->regenerateToken();
return redirect(‘/’);
}
}
授权策略(Policies)
php artisan make:policy PostPolicy –model=Post
创建
app/Policies/PostPolicy.php
:
status === ‘published’ || $user->id === $post->user_id;
}
/**
* 确定用户是否可以创建文章
*/
public function create(User $user): bool
{
return $user->is_active; // 只有活跃用户可以创建
}
/**
* 确定用户是否可以更新文章
*/
public function update(User $user, Post $post): bool
{
return $user->id === $post->user_id;
}
/**
* 确定用户是否可以删除文章
*/
public function delete(User $user, Post $post): bool
{
return $user->id === $post->user_id || $user->isAdmin();
}
}
在控制器中使用授权:
authorize(‘view’, $post);
return view(‘posts.show’, compact(‘post’));
}
public function edit(Post $post)
{
// 简写方式
$this->authorize(‘update’, $post);
return view(‘posts.edit’, compact(‘post’));
}
// 在路由模型绑定中自动授权
public function destroy(Post $post)
{
// 如果授权失败,会自动抛出403异常
$this->authorize(‘delete’, $post);
$post->delete();
return redirect()->route(‘posts.index’)->with(‘success’, ‘文章已删除’);
}
}
中间件与请求处理
创建自定义中间件
php artisan make:middleware CheckPostOwner
创建
app/Http/Middleware/CheckPostOwner.php
:
route(‘post’);
$post = Post::findOrFail($postId);
if ($post->user_id !== auth()->id() && !auth()->user()->isAdmin()) {
return response()->json([‘error’ => ‘无权操作’], 403);
}
return $next($request);
}
}
在路由中使用中间件:
Route::middleware([‘auth’, ‘post.owner’])->group(function () {
Route::put(‘/posts/{post}’, [PostController::class, ‘update’]);
Route::delete(‘/posts/{post}’, [PostController::class, ‘destroy’]);
});
实战项目:博客系统开发
项目结构规划
my-blog/
├── app/
│ ├── Http/
│ │ ├── Controllers/
│ │ │ ├── PostController.php
│ │ │ ├── CommentController.php
│ │ │ └── DashboardController.php
│ │ └── Requests/
│ │ ├── StorePostRequest.php
│ │ └── StoreCommentRequest.php
│ ├── Models/
│ │ ├── Post.php
│ │ ├── Comment.php
│ │ └── Tag.php
│ ├── Policies/
│ │ ├── PostPolicy.php
│ │ └── CommentPolicy.php
│ └── View/Components/
│ └── PostCard.php
├── database/
│ ├── migrations/
│ │ ├── 2023_01_01_000001_create_users_table.php
│ │ ├── 2023_01_01_000002_create_posts_table.php
│ │ ├── 2023_01_01_000003_create_comments_table.php
│ │ └── 2023_01_01_000004_create_tags_table.php
│ └── seeders/
│ ├── DatabaseSeeder.php
│ └── PostSeeder.php
├── resources/
│ ├── views/
│ │ ├── layouts/
│ │ │ └── app.blade.php
│ │ ├── posts/
│ │ │ ├── index.blade.php
│ │ │ ├── show.blade.php
│ │ │ ├── create.blade.php
│ │ │ ├── edit.blade.php
│ │ │ └── partials/
│ │ │ ├── card.blade.php
│ │ │ └── comment.blade.php
│ │ ├── dashboard/
│ │ │ └── index.blade.php
│ │ └── welcome.blade.php
│ └── components/
│ └── button.blade.php
├── routes/
│ ├── web.php
│ └── api.php
└── tests/
└── Feature/
└── PostTest.php
完整的路由配置
name(‘home’);
// 认证路由
Route::middleware([‘auth’])->group(function () {
// 仪表盘
Route::get(‘/dashboard’, [DashboardController::class, ‘index’])->name(‘dashboard’);
// 文章管理(资源路由)
Route::resource(‘posts’, PostController::class)->except([‘index’, ‘show’]);
// 评论管理
Route::post(‘/posts/{post}/comments’, [CommentController::class, ‘store’])->name(‘comments.store’);
Route::delete(‘/comments/{comment}’, [CommentController::class, ‘destroy’])->name(‘comments.destroy’);
});
// 公开路由
Route::get(‘/posts/{post}’, [PostController::class, ‘show’])->name(‘posts.show’);
Route::get(‘/posts’, [PostController::class, ‘index’])->name(‘posts.index’);
// 认证相关(Laravel Breeze 生成)
require __DIR__.’/auth.php’;
数据库迁移完整示例
boolean(‘is_admin’)->default(false);
$table->boolean(‘is_active’)->default(true);
$table->string(‘avatar’)->nullable();
});
// 文章表
Schema::create(‘posts’, function (Blueprint $table) {
$table->id();
$table->foreignId(‘user_id’)->constrained()->onDelete(‘cascade’);
$table->string(‘title’);
$table->string(‘slug’)->unique();
$table->text(‘content’);
$table->enum(‘status’, [‘draft’, ‘published’])->default(‘draft’);
$table->integer(‘view_count’)->default(0);
$table->timestamps();
$table->softDeletes();
// 索引
$table->index([‘status’, ‘created_at’]);
$table->index(‘user_id’);
});
// 评论表
Schema::create(‘comments’, function (Blueprint $table) {
$table->id();
$table->foreignId(‘user_id’)->constrained()->onDelete(‘cascade’);
$table->foreignId(‘post_id’)->constrained()->onDelete(‘cascade’);
$table->text(‘content’);
$table->foreignId(‘parent_id’)->nullable()->constrained(‘comments’)->onDelete(‘cascade’);
$table->timestamps();
$table->index([‘post_id’, ‘created_at’]);
});
// 标签表
Schema::create(‘tags’, function (Blueprint $table) {
$table->id();
$table->string(‘name’)->unique();
$table->string(‘slug’)->unique();
$table->timestamps();
});
// 多对多关系表
Schema::create(‘post_tags’, function (Blueprint $table) {
$table->foreignId(‘post_id’)->constrained()->onDelete(‘cascade’);
$table->foreignId(‘tag_id’)->constrained()->onDelete(‘cascade’);
$table->primary([‘post_id’, ‘tag_id’]);
});
}
public function down()
{
Schema::dropIfExists(‘post_tags’);
Schema::dropIfExists(‘tags’);
Schema::dropIfExists(‘comments’);
Schema::dropIfExists(‘posts’);
Schema::table(‘users’, function (Blueprint $table) {
$table->dropColumn([‘is_admin’, ‘is_active’, ‘avatar’]);
});
}
};
数据填充
‘管理员’,
’email’ => ‘admin@example.com’,
‘password’ => bcrypt(‘password’),
‘is_admin’ => true,
]);
// 创建普通用户
$user = User::create([
‘name’ => ‘测试用户’,
’email’ => ‘user@example.com’,
‘password’ => bcrypt(‘password’),
]);
// 创建标签
$tags = [‘Laravel’, ‘PHP’, ‘Web开发’, ‘数据库’, ‘前端’];
$tagModels = [];
foreach ($tags as $tag) {
$tagModels[] = Tag::create([
‘name’ => $tag,
‘slug’ => \Illuminate\Support\Str::slug($tag),
]);
}
// 创建文章
$posts = Post::factory(20)->create([‘user_id’ => $user->id]);
// 为文章分配标签
$posts->each(function ($post) use ($tagModels) {
$post->tags()->attach(
$tagModels->random(rand(1, 3))->pluck(‘id’)
);
// 为每篇文章创建评论
Comment::factory(rand(2, 5))->create([
‘post_id’ => $post->id,
‘user_id’ => User::inRandomOrder()->first()->id,
]);
});
// 创建一些管理员的文章
Post::factory(5)->create([‘user_id’ => $admin->id]);
}
}
控制器完整实现
middleware(‘auth’)->except([‘index’, ‘show’]);
$this->middleware(‘can:view,post’)->only(‘show’);
$this->middleware(‘can:update,post’)->only(‘edit’, ‘update’);
$this->middleware(‘can:delete,post’)->only(‘destroy’);
}
/**
* 文章列表(带缓存)
*/
public function index(Request $request)
{
$cacheKey = ‘posts.page.’ . $request->page . ‘.search.’ . $request->search;
$posts = Cache::remember($cacheKey, 300, function () use ($request) {
$query = Post::with([‘user’, ‘tags’])
->withCount(‘comments’)
->published()
->orderBy(‘created_at’, ‘desc’);
if ($request->search) {
$query->search($request->search);
}
return $query->paginate(10);
});
return view(‘posts.index’, compact(‘posts’));
}
/**
* 显示单篇文章
*/
public function show(Post $post)
{
// 增加浏览数(使用缓存避免频繁写入)
Cache::remember(“post_views_{$post->id}”, 60, function () use ($post) {
$post->increment(‘view_count’);
return true;
});
// 获取评论(支持分页)
$comments = $post->comments()->with(‘user’)->paginate(5);
return view(‘posts.show’, compact(‘post’, ‘comments’));
}
/**
* 创建文章表单
*/
public function create()
{
$this->authorize(‘create’, Post::class);
return view(‘posts.create’);
}
/**
* 存储新文章
*/
public function store(StorePostRequest $request)
{
$validated = $request->validated();
$post = Post::create([
…$validated,
‘user_id’ => auth()->id(),
‘slug’ => \Illuminate\Support\Str::slug($validated[‘title’]),
]);
// 清除相关缓存
Cache::tags([‘posts’])->flush();
return redirect()->route(‘posts.show’, $post)
->with(‘success’, “文章「{$post->title}」创建成功!”);
}
/**
* 编辑文章表单
*/
public function edit(Post $post)
{
return view(‘posts.edit’, compact(‘post’));
}
/**
* 更新文章
*/
public function update(StorePostRequest $request, Post $post)
{
$validated = $request->validated();
$post->update($validated);
// 清除缓存
Cache::tags([‘posts’])->flush();
return redirect()->route(‘posts.show’, $post)
->with(‘success’, “文章「{$post->title}」更新成功!”);
}
/**
* 删除文章
*/
public function destroy(Post $post)
{
$title = $post->title;
$post->delete();
// 清除缓存
Cache::tags([‘posts’])->flush();
return redirect()->route(‘posts.index’)
->with(‘success’, “文章「{$title}」已删除!”);
}
}
评论控制器
comments()->create([
…$request->validated(),
‘user_id’ => auth()->id(),
]);
// 如果是Ajax请求,返回JSON
if ($request->ajax()) {
return response()->json([
‘success’ => true,
‘comment’ => [
‘content’ => $comment->content,
‘user’ => $comment->user->name,
‘created_at’ => $comment->created_at->diffForHumans(),
]
]);
}
return back()->with(‘success’, ‘评论添加成功!’);
}
public function destroy(Comment $comment)
{
$this->authorize(‘delete’, $comment);
$comment->delete();
return back()->with(‘success’, ‘评论已删除’);
}
}
测试与调试
创建测试
php artisan make:test PostTest
编写测试用例:
create();
$post = Post::factory()->create([‘status’ => ‘published’, ‘user_id’ => $user->id]);
$response = $this->get(‘/posts’);
$response->assertStatus(200);
$response->assertSee($post->title);
}
/** @test */
public function authenticated_user_can_create_post()
{
$user = User::factory()->create();
$this->actingAs($user)->post(‘/posts’, [
‘title’ => ‘Test Post’,
‘content’ => ‘Test content’,
‘status’ => ‘published’,
]);
$this->assertDatabaseHas(‘posts’, [
‘title’ => ‘Test Post’,
‘user_id’ => $user->id,
]);
}
/** @test */
public function only_owner_can_update_post()
{
$owner = User::factory()->create();
$otherUser = User::factory()->create();
$post = Post::factory()->create([‘user_id’ => $owner->id]);
// 尝试用其他用户身份更新
$this->actingAs($otherUser)
->put(“/posts/{$post->id}”, [
‘title’ => ‘Hacked Title’,
‘content’ => ‘Hacked content’,
‘status’ => ‘published’,
])
->assertForbidden();
// 验证数据未被修改
$this->assertDatabaseMissing(‘posts’, [
‘title’ => ‘Hacked Title’,
]);
}
}
运行测试:
# 运行所有测试
php artisan test
# 运行特定测试
php artisan test –filter PostTest
# 详细输出
php artisan test –verbose
调试技巧
// 使用dd()调试并终止
dd($post);
// 使用dump()调试但不终止
dump($post);
// 使用Log记录
use Illuminate\Support\Facades\Log;
Log::info(‘文章创建’, [‘post_id’ => $post->id, ‘user_id’ => auth()->id()]);
Log::error(‘数据库错误’, [‘error’ => $e->getMessage()]);
// 在Blade中调试
@php
dd($post);
@endphp
// 使用Laravel Telescope进行调试(开发环境)
composer require laravel/telescope –dev
php artisan telescope:install
php artisan migrate
部署与性能优化
生产环境优化配置
# 优化自动加载
composer install –optimize-autoloader –no-dev
# 优化配置缓存
php artisan config:cache
# 优化路由缓存
php artisan route:cache
# 优化视图缓存
php artisan view:cache
# 运行队列worker(如果有队列任务)
php artisan queue:work –daemon
性能优化技巧
// 1. 使用缓存
use Illuminate\Support\Facades\Cache;
$posts = Cache::remember(‘posts.index’, 300, function () {
return Post::with(‘user’)->published()->get();
});
// 2. 预加载关系(避免N+1问题)
$posts = Post::with([‘user’, ‘comments.user’])->get();
// 3. 使用Eloquent API资源
php artisan make:resource PostResource
// PostResource.php
class PostResource extends JsonResource
{
public function toArray($request)
{
return [
‘id’ => $this->id,
‘title’ => $this->title,
‘content’ => $this->content,
‘user’ => new UserResource($this->user),
‘created_at’ => $this->created_at,
];
}
}
// 在控制器中使用
return PostResource::collection($posts);
// 4. 数据库索引
// 在迁移中添加
$table->index([‘status’, ‘created_at’]);
$table->index(‘user_id’);
// 5. 分页优化
$posts = Post::paginate(10, [‘*’], ‘page’, $page);
部署脚本示例
#!/bin/bash
# deploy.sh
echo “开始部署…”
# 进入项目目录
cd /var/www/my-app
# 拉取最新代码
git pull origin main
# 安装依赖
composer install –no-dev –optimize-autoloader
# 复制环境配置
cp .env.production .env
# 生成应用密钥(如果不存在)
php artisan key:generate –show
# 运行迁移
php artisan migrate –force
# 优化
php artisan config:cache
php artisan route:cache
php artisan view:cache
# 重启队列worker
php artisan queue:restart
# 设置权限
chown -R www-data:www-data storage bootstrap/cache
chmod -R 775 storage bootstrap/cache
echo “部署完成!”
最佳实践与进阶技巧
代码组织最佳实践
单一职责原则
:每个类只做一件事
资源控制器
:使用
php artisan make:controller –resource
生成标准CRUD
表单请求
:将验证逻辑分离到Form Request
策略类
:使用Policy处理授权逻辑
服务类
:复杂业务逻辑放入服务类
仓库模式
:数据访问层分离(可选)
安全最佳实践
// 1. 防止XSS:自动转义输出
{{ $userInput }} // 自动转义
// 2. 防止SQL注入:使用Eloquent或参数绑定
Post::where(‘title’, $input)->get(); // 安全
// 3. CSRF保护:表单必须包含@csrf
@csrf
// 4. 文件上传验证
$request->validate([
‘avatar’ => ‘required|image|mimes:jpeg,png,jpg|max:2048’,
]);
// 5. 防止批量赋值
protected $fillable = [‘title’, ‘content’]; // 只允许这些字段
// 或
protected $guarded = [‘id’, ‘user_id’]; // 禁止这些字段
性能监控
// 使用Laravel Debugbar(开发环境)
composer require barryvdh/laravel-debugbar –dev
// 在AppServiceProvider中监控查询
public function boot()
{
if (config(‘app.debug’)) {
\DB::listen(function ($query) {
if ($query->time > 100) {
\Log::warning(“慢查询: {$query->sql} ({$query->time}ms)”);
}
});
}
}
总结与学习路径
通过本指南,你已经学习了Laravel MVC开发的完整流程:
✅
环境搭建
:安装Laravel和配置开发环境
✅
MVC架构
:理解并实现Model、View、Controller
✅
路由系统
:定义和管理应用路由
✅
数据库操作
:迁移、模型、Eloquent ORM
✅
视图开发
:Blade模板引擎和组件
✅
表单验证
:数据验证和错误处理
✅
认证授权
:用户认证和权限管理
✅
中间件
:请求过滤和处理
✅
实战项目
:完整的博客系统开发
✅
测试调试
:编写测试和调试技巧
✅
部署优化
:生产环境部署和性能优化
下一步学习建议
深入学习Laravel特性
:
队列系统(Queues)
事件系统(Events)
广播系统(Broadcasting)
文件存储(File Storage)
API开发(Sanctum/Passport)
探索高级包
:
Laravel Nova(管理面板)
Laravel Horizon(队列监控)
Laravel Telescope(调试工具)
Laravel Cashier(支付集成)
实践项目
:
构建RESTful API
开发实时应用(使用Pusher/Redis)
构建多语言应用
实现文件上传和处理
社区资源
:
Laravel官方文档
Laravel News
Laracasts视频教程
Laravel China社区
记住,Laravel是一个不断发展的框架,保持学习和实践是掌握它的关键。祝你在Laravel开发之旅中取得成功!