- 2017 版 Laravel 系列入门教程
- https://github.com/OMGZui/noteBook/tree/master/php/laravel
- Laravel 完整开源项目大全
- https://github.com/summerblue/laravel5-cheatsheet | https://cs.laravel-china.org/
- https://github.com/summerblue/laravel-shop
- https://github.com/z-song/laravel-admin
- Laravel 5.8 中文文档
- 上线清单 —— 20 个 Laravel 应用性能优化项
make
db
migrate
key
vendor
环境变量
数据库
应用配置
路由
读写分离
多库连接
Migration
Seeder
类定义
属性
方法
布局
区块
分页
赋值
循环
条件
错误日志
composer create-project laravel/laravel learnlaravel5 ^5.5
设置文件夹权限
chmod 777 -R storage bootstrap/cache
Artisan 命令行 Laravel Artisan常用命令
# 所有命令列表
php artisan list
# 命令帮助
php artisan help migrate
php artisan make:auth
php artisan make:middleware XXX
php artisan make:model Article
php artisan make:model Comment -m
# linux or macOs 加上转义符
php artisan make:Model App\\Models\\User
# 创建表及其迁移
php artisan make:model --migration Post
# 创建迁移
php artisan make:migration create_articles_table
# 指定路径
php artisan make:migration --path=app\providers create_users_table
# 创建要填充的数据类
php artisan make:seeder ArticleSeeder
php artisan make:controller ArticleController
# REST 风格
php artisan make:controller CommentController --resource
php artisan make:controller Admin/HomeController
主要用于表单验证
app/Http/Requests/
php artisan make:request TagCreateRequest
app/Console/Commands/
php artisan make:console TopicMakeExcerptCommand --command=topics:excerpt123
php artisan make:command SendEmails
在 app/Console/Kernel.php 文件里面,添加以下
protected $commands = [
\App\Console\Commands\TopicMakeExcerptCommand::class,
];
# 数据填充(全部表)
php artisan db:seed
# 指定要填充的表
php artisan db:seed --class=UsersTableSeeder
# 数据迁移
php artisan migrate
php artisan key:generate
# 自定义分页视图
php artisan vendor:publish --tag=laravel-pagination
# 查看所有路由
php artisan route:list
.env
# 应用
APP_NAME=Laravel
APP_ENV=local
APP_DEBUG=true
APP_URL=http://localhost
APP_KEY=base64:+US9WuCFNDh0EMF38Ud6bZDO3McW+58f5iipZvTZF/s=
# 数据库
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel5
DB_USERNAME=root
DB_PASSWORD=root
config/database.php
database/
config\app.php
return [
'name' => env('APP_NAME', 'Laravel'),
'env' => env('APP_ENV', 'production'),
'debug' => env('APP_DEBUG', false),
'url' => env('APP_URL', 'http://localhost'),
'asset_url' => env('ASSET_URL', null),
'timezone' => 'UTC',
'locale' => 'en',
'fallback_locale' => 'en',
'faker_locale' => 'en_US',
'key' => env('APP_KEY'),
'chipher' => 'AES-256-CBC',
'providers' => [
/*
* Laravel Framework Service Providers...
*/
Illuminate\Auth\AuthServiceProvider::class,
/*
* Package Service Providers...
*/
/*
* Application Service Providers...
*/
App\Providers\AppServiceProvider::class,
],
'aliases' => [
'App' => Illuminate\Support\Facades\App::class,
],
];
routes/web.php
Route::group(['middleware' => 'auth', 'namespace' => 'Admin', 'prefix' => 'admin'], function() {
Route::get('/', 'HomeController@index');
});
Route::has('login')
Auth::routes();
Route::get('/home', 'HomeController@index')->name('home');
app/Http/Controllers/
use Illuminate\Routing\Controller as BaseController; //abstract
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Foundation\Validation\ValidatesRequests;
class Controller extends BaseController
{
use AuthorizesRequests, DispatchesJobs, ValidatesRequests; //trait
}
use Illuminate\Http\Request; //HTTP请求
class HomeController extends Controller
{
public function __construct()
{
$this->middleware('auth');
}
public function index(Request $request)
{
$data = [
'input' => $request->input('i', 'in'),
'query' => $request->query('q', 'qu'),
];
return view('home.index', $data); //视图
}
}
namespace Illuminate\Http;
use ArrayAccess;
use Illuminate\Contracts\Support\Arrayable;
use Symfony\Component\HttpFoundation\Request as SymfonyRequest;
class Request extends SymfonyRequest implements Arrayable, ArrayAccess
{
}
基于Laravel5.5的模块化开发 => https://gitee.com/techlee/laravel5.5-modules-demo
Laravel 模块化开发 => https://github.com/nWidart/laravel-modules
使用 Laravel-Modules 扩展包通过模块化开发大型 Laravel 应用
Laravel 怎么实现分模块,求大牛详解 => https://github.com/caffeinated/modules
基于 Laravel 5 构建的、支持模块化和多语言的 CMS —— AsgardCMS => https://github.com/AsgardCms
定义
use Illuminate\Support\Facades\DB;
使用
DB::select($sql, [$id]);
'mysql' => [
'read' => [
'host' => ['192.168.1.1'],
],
'write' => [
'host' => ['196.168.1.2'],
],
'sticky' => true, // 可选项 请求周期内执行过写操作,那么读操作将使用写连接
],
// 连接方法
$users = DB::connection('foo')->select(...);
// 实例
$pdo = DB::connection()->getPdo();
DB::table($table_name)
from($table_name)
join($table, $column, '=', $field) //Inner Join
join('contacts', function ($join) {
$join->on('users.id', '=', 'contacts.user_id')->orOn(...);
}) //高级 Join 语句
leftJoin()
crossJoin()
$first = Db::table('users');
union($first)
unionAll()
DB::raw($sql_str) //转换部分
selectRaw($sql_str, $arg_arr) //方法
whereRaw()
orWhereRaw()
havingRaw()
orHavingRaw()
orderByRaw()
namespace App;
use Illuminate\Database\Eloquent\Model; //abstract
class DbTable extends Model
{
protected $connection = 'mysql';
protected $table = 'test';
protected $fillable = [
'name', 'email', 'password',
];
protected $hidden = [
'password', 'remember_token',
];
public function __construct(array $attributes = [])
{
parent::__construct($attributes);
}
}
多库连接
// 模型里添加属性
protected $connection = 'mysql';
select($col, $col2...) //字段
addSelect($column) //添加字段
distinct() //不重复的结果
where($field, $value)
where($field, '>', $value)
where([
[$field, '>', $value],
])
where('preferences->dining->meal', 'salad') //JSON 支持
orWhere() //同上
orWhere(function ($query) {
$query->where()->where();
}) //参数分组
whereExists(function ($query) {
$query->select(DB::raw(1))
->from('orders')
->whereRaw('orders.user_id = users.id');
})
whereBetween('created_at', [$start, $end])
whereNotBetween()
whereIn($column, $arr)
whereNotIn()
whereNull($field)
whereNotNull()
whereDate($field, $value)
whereMonth
whereDay
whereYear
whereTime($field, '=', $value)
whereColumn($col, $col2)
whereColumn($col, '>', $col2)
whereColumn([])
find($id)
when($sortBy, function ($query) use ($sortBy) {
return $query->orderBy($sortBy);
}, function ($query) {
return $query->orderBy('name');
})
groupBy($column)
having($field, '=', $value)
orderBy(field, 'desc')
// 日期排序,默认 created_at 字段
latest()
oldest()
inRandomOrder() //随机
offset(0)->limit(10)
// 等价于
skip(3)->take(3)
paginate(40)
simplePaginate(15)
get() //所有行
first() //单个行
value($column) //单个列
pluck($column_value, $key) //获取列
chunk($limit, function ($all) {}) //结果分块
count()
max($column)
min($colmun)
avg($column)
sum($column)
insert(
['email' => '[email protected]', 'votes' => 0]
)
// 插入多条
insert([
['email' => '[email protected]', 'votes' => 0],
['email' => '[email protected]', 'votes' => 0]
])
// 自增 ID
insertGetId(
['email' => '[email protected]', 'votes' => 0]
)
update($data_arr)
update(['options->enabled' => true]) //更新 JSON 字段
自增 & 自减
increment($field)
decrement('votes', 5, ['name' => 'John'])
delete()
truncate() //清空
sharedLock() //共享锁
lockForUpdate() //更新锁
@extends('layouts.app')
// 定义
@section('content')
// 内容
@endsection
// 引用
@yield('content')
withPath('custom/url')
appends(['sort' => 'votes'])
fragment('foo')
onEachSide(5)
toJson()
// 定义参见上面模型分页
// 视图中引用
links()
links('view.name', ['foo' => 'bar'])
return view('home')->withArticles(\App\Article::all());
# 等价于
->with('articles', \App\Article::all())
->withFooBar(100)
# 等价于
->with('foo_bar', 100)
@foreach ($articles as $article)
{{ url('article/'.$article->id) }}
@endforeach
@if (session('status'))
{{ session('status') }}
@endif
app()->getLocale()
storage/logs/
.env 中 APP_KEY 为空,执行以下命令
php artisan key:generate
缺少 .env