Laravel 6 速查表

路由 (Routing)

// 基础路由
Route::get('/welcome', function () {
    return view('welcome');
});
        
// 带参数路由
Route::get('/user/{id}', function ($id) {
    return 'User '.$id;
});
        
// 控制器路由
Route::get('/user', 'UserController@index');

数据库 (Eloquent)

// 获取所有记录
$users = User::all();
        
// 条件查询
$users = User::where('votes', '>', 100)
    ->orderBy('name', 'desc')
    ->take(10)
    ->get();

// 创建记录
$user = User::create([
    'name' => 'John',
    'email' => 'john@example.com'
]);

Blade 模板

// 显示变量
{{ $variable }}

// 条件语句
@if (count($records) === 1)
    有一条记录
@elseif (count($records) > 1)
    有多条记录
@else
    没有记录
@endif

// 循环
@foreach ($users as $user)
    {{ $user->name }}
@endforeach

中间件 (Middleware)

// 路由中使用中间件
Route::get('/profile', function () {
    // 只有认证用户可以访问
})->middleware('auth');

// 创建中间件
php artisan make:middleware CheckAge

表单验证

// 控制器中验证
$validatedData = $request->validate([
    'title' => 'required|unique:posts|max:255',
    'body' => 'required',
]);

// 自定义错误消息
$messages = [
    'required' => 'The :attribute field is required.',
];

$validator = Validator::make($input, $rules, $messages);

数组辅助方法 (Arr)

// 获取数组值,支持点号语法
$array = ['products' => ['desk' => ['price' => 100]]];
$price = Arr::get($array, 'products.desk.price'); // 100

// 检查数组是否包含键
$array = ['name' => 'John', 'age' => 30];
$hasName = Arr::has($array, 'name'); // true

// 数组排序
$array = ['Desk', 'Table', 'Chair'];
$sorted = Arr::sort($array); // ['Chair', 'Desk', 'Table']

// 数组扁平化
$array = ['name' => 'John', 'languages' => ['php', 'python']];
$flattened = Arr::flatten($array); // ['John', 'php', 'python']

// 数组过滤
$array = ['product' => 'Desk', 'price' => 100, 'discount' => false];
$filtered = Arr::where($array, function ($value, $key) {
    return is_string($value);
}); // ['product' => 'Desk']

字符串辅助方法 (Str)

// 字符串转驼峰
$converted = Str::camel('foo_bar'); // fooBar

// 字符串转蛇形
$converted = Str::snake('fooBar'); // foo_bar

// 字符串截断
$truncated = Str::limit('The quick brown fox jumps over the lazy dog', 20); 
// The quick brown fox...

// 字符串随机生成
$random = Str::random(40); // 40位随机字符串

// 字符串包含判断
$contains = Str::contains('This is my name', 'my'); // true

// 字符串开头判断
$startsWith = Str::startsWith('This is a sentence', 'This'); // true

// 字符串结尾判断
$endsWith = Str::endsWith('This is a sentence', 'sentence'); // true

// 字符串替换
$string = 'The event will take place between ? and ?';
$replaced = Str::replaceArray('?', ['8:30', '9:00'], $string);
// The event will take place between 8:30 and 9:00

缓存 (Cache)

// 存储缓存
Cache::put('key', 'value', $minutes = 10);

// 永久存储
Cache::forever('key', 'value');

// 获取缓存
$value = Cache::get('key');

// 获取或存储
$value = Cache::remember('users', $minutes, function () {
    return DB::table('users')->get();
});

// 删除缓存
Cache::forget('key');

// 检查缓存是否存在
if (Cache::has('key')) {
    //
}

队列 (Queue)

// 分发任务到队列
ProcessPodcast::dispatch($podcast);

// 延迟分发
ProcessPodcast::dispatch($podcast)->delay(now()->addMinutes(10));
                
// 同步执行(不排队)
ProcessPodcast::dispatchSync($podcast);

// 创建队列任务
php artisan make:job ProcessPodcast

// 队列监听
php artisan queue:listen
php artisan queue:work

事件 (Events)

// 创建事件
php artisan make:event OrderShipped

// 创建监听器
php artisan make:listener SendShipmentNotification

// 触发事件
event(new OrderShipped($order));

// 监听事件
protected $listen = [
    OrderShipped::class => [
        SendShipmentNotification::class,
    ],
];

邮件 (Mail)

// 创建邮件类
php artisan make:mail OrderShipped

// 发送邮件
Mail::to($request->user())
    ->cc($moreUsers)
    ->bcc($evenMoreUsers)
    ->send(new OrderShipped($order));

// 邮件预览
return new OrderShipped($order);

// 队列邮件
Mail::to($request->user())->queue(new OrderShipped($order));

文件存储 (Filesystem)

// 存储文件
Storage::put('file.jpg', $contents);

// 获取文件
$contents = Storage::get('file.jpg');

// 检查文件是否存在
if (Storage::exists('file.jpg')) {
    //
}

// 下载文件
return Storage::download('file.jpg');

// 文件URL
$url = Storage::url('file.jpg');

// 删除文件
Storage::delete('file.jpg');

基础验证规则

// 必填字段
'name' => 'required'

// 数字验证
'age' => 'integer|min:18|max:65|digits:2'

// 字符串验证
'title' => 'string|max:255|min:5'

// 邮箱验证
'email' => 'email:rfc,dns'

// URL验证
'website' => 'url|active_url'

// 唯一性验证
'email' => 'unique:users,email_address,except,id'

// 确认字段匹配
'password' => 'confirmed|same:password_confirmation'

// 日期验证
'birthday' => 'date|after:2000-01-01|before:today'

// 文件验证
'avatar' => 'file|image|mimes:jpeg,png|max:2048'

// 数组验证
'users.*.email' => 'email'

// 正则验证
'username' => 'regex:/^[a-z0-9_]+$/'

// IP地址验证
'ip' => 'ipv4'

// JSON验证
'metadata' => 'json'
        

高级验证规则

// 条件验证
'payment_method' => 'required_if:subscription,true|required_unless:subscription,false'

// 自定义错误消息
$messages = [
    'required' => '请填写 :attribute 字段',
    'email' => '请输入有效的邮箱地址',
    'min' => [
        'string' => ':attribute 至少需要 :min 个字符',
        'numeric' => ':attribute 不能小于 :min'
    ]
];

// 自定义验证规则
Validator::extend('foo', function ($attribute, $value, $parameters, $validator) {
    return $value == 'foo';
});