Laravel 10 开发技巧汇总

Laravel 10 实用开发技巧

Laravel是最流行的PHP框架,本文分享一些实用的开发技巧。

1. 查询作用域(Query Scopes)

class User extends Model {
    public function scopeActive($query) {
        return $query->where('status', 'active');
    }
    
    public function scopePopular($query) {
        return $query->where('votes', '>', 100);
    }
}

// 使用
$users = User::active()->popular()->get();

2. 访问器和修改器

// 访问器
public function getFullNameAttribute() {
    return "{$this->first_name} {$this->last_name}";
}

// 修改器
public function setPasswordAttribute($value) {
    $this->attributes['password'] = bcrypt($value);
}

3. 批量赋值保护

protected $fillable = ['name', 'email'];
protected $guarded = ['id', 'password'];

4. 关联关系预加载

// 避免N+1问题
$books = Book::with('author')->get();

// 嵌套预加载
$books = Book::with('author.contacts')->get();

5. 队列任务

// 创建任务
php artisan make:job SendEmail

// 分发任务
SendEmail::dispatch($user);

掌握这些技巧,让Laravel开发更高效!

最后更新: 2026-01-10 08:59