下面由laravel教程栏目带大家介绍新鲜出炉的laravel 速查表,希望对大家有所帮助!
Laravel 速查表
项目命令
// 创建新项目 $ laravel new projectName // 运行 服务/项目 $ php artisan serve // 查看指令列表 $ php artisan list // 帮助 $ php artisan help migrate // Laravel 控制台 $ php artisan tinker // 查看路由列表 $ php artisan route:list
公共指令
// 数据库迁移 $ php artisan migrate // 数据填充 $ php artisan db:seed // 创建数据表迁移文件 $ php artisan make:migration create_products_table // 生成模型选项: // -m (migration), -c (controller), -r (resource controllers), -f (factory), -s (seed) $ php artisan make:model Product -mcf // 生成控制器 $ php artisan make:controller ProductsController // 表更新字段 $ php artisan make:migration add_date_to_blogposts_table // 回滚上一次迁移 php artisan migrate:rollback // 回滚所有迁移 php artisan migrate:reset // 回滚所有迁移并刷新 php artisan migrate:refresh // 回滚所有迁移,刷新并生成数据 php artisan migrate:refresh --seed
创建和更新数据表
// 创建数据表
$ php artisan make:migration create_products_table
// 创建数据表(迁移示例)
Schema::create('products', function (Blueprint $table) {
// 自增主键
$table->id();
// created_at 和 updated_at 字段
$table->timestamps();
// 唯一约束
$table->string('modelNo')->unique();
// 非必要
$table->text('description')->nullable();
// 默认值
$table->boolean('isActive')->default(true);
// 索引
$table->index(['account_id', 'created_at']);
// 外键约束
$table->foreignId('user_id')->constrained('users')->onDelete('cascade');
});
// 更新表(迁移示例)
$ php artisan make:migration add_comment_to_products_table
// up()
Schema::table('users', function (Blueprint $table) {
$table->text('comment');
});
// down()
Schema::table('users', function (Blueprint $table) {
$table->dropColumn('comment');
});模型
// 模型质量指定列表排除属性
protected $guarded = []; // empty == All
// 或者包含属性的列表
protected $fillable = ['name', 'email', 'password',];
// 一对多关系 (一条帖子对应多条评论)
public function comments()
{
return $this->hasMany(Comment:class);
}
// 一对多关系 (多条评论在一条帖子下)
public function post()
{
return $this->belongTo(Post::class);
}
// 一对一关系 (作者和个人简介)
public function profile()
{
return $this->hasOne(Profile::class);
}
// 一对一关系 (个人简介和作者)
public function author()
{
return $this->belongTo(Author::class);
}
// 多对多关系
// 3 张表 (帖子, 标签和帖子-标签)
// 帖子-标签:post_tag (post_id, tag_id)
// 「标签」模型中...
public function posts()
{
return $this->belongsToMany(Post::class);
}
// 帖子模型中...
public function tags()
{
return $this->belongsToMany(Tag::class);
}Factory
// 例子: database/factories/ProductFactory.php
public function definition() {
return [
'name' => $this->faker->text(20),
'price' => $this->faker->numberBetween(10, 10000),
];
}
// 所有 fakers 选项 : https://github.com/fzaninotto/FakerSeed
// 例子: database/seeders/DatabaseSeeder.php
public function run() {
Product::factory(10)->create();
}运行 Seeders
$ php artisan db:seed // 或者 migration 时执行 $ php artisan migrate --seed
Eloquent ORM
// 新建
$flight = new Flight;
$flight->name = $request->name;
$flight->save();
// 更新
$flight = Flight::find(1);
$flight->name = 'New Flight Name';
$flight->save();
// 创建
$user = User::create(['first_name' => 'Taylor','last_name' => 'Otwell']);
// 更新所有:
Flight::where('active', 1)->update(['delayed' => 1]);
// 删除
$current_user = User::Find(1)
$current_user.delete();
// 根据 id 删除:
User::destroy(1);
// 删除所有
$deletedRows = Flight::where('active', 0)->delete();
// 获取所有
$items = Item::all().
// 根据主键查询一条记录
$flight = Flight::find(1);
// 如果不存在显示 404
$model = Flight::findOrFail(1);
// 获取最后一条记录
$items = Item::latest()->get()
// 链式
$flights = App\Flight::where('active', 1)->orderBy('name', 'desc')->take(10)->get();
// Where
Todo::where('id', $id)->firstOrFail()
// Like
Todos::where('name', 'like', '%' . $my . '%')->get()
// Or where
Todos::where('name', 'mike')->orWhere('title', '=', 'Admin')->get();
// Count
$count = Flight::where('active', 1)->count();
// Sum
$sum = Flight::where('active', 1)->sum('price');
// Contain?
if ($project->$users->contains('mike'))路由
// 基础闭包路由
Route::get('/greeting', function () {
return 'Hello World';
});
// 视图路由快捷方式
Route::view('/welcome', 'welcome');
// 路由到控制器
use App\Http\Controllers\UserController;
Route::get('/user', [UserController::class, 'index']);
// 仅针对特定 HTTP 动词的路由
Route::match(['get', 'post'], '/', function () {
//
});
// 响应所有 HTTP 请求的路由
Route::any('/', function () {
//
});
// 重定向路由
Route::redirect('/clients', '/customers');
// 路由参数
Route::get('/user/{id}', function ($id) {
return 'User '.$id;
});
// 可选参数
Route::get('/user/{name?}', function ($name = 'John') {
return $name;
});
// 路由命名
Route::get(
'/user/profile',
[UserProfileController::class, 'show']
)->name('profile');
// 资源路由
Route::resource('photos', PhotoController::class);
GET /photos index photos.index
GET /photos/create create photos.create
POST /photos store photos.store
GET /photos/{photo} show photos.show
GET /photos/{photo}/edit edit photos.edit
PUT/PATCH /photos/{photo} update photos.update
DELETE /photos/{photo} destroy photos.destroy
// 完整资源路由
Route::resource('photos.comments', PhotoCommentController::class);
// 部分资源路由
Route::resource('photos', PhotoController::class)->only([
'index', 'show'
]);
Route::resource('photos', PhotoController::class)->except([
'create', 'store', 'update', 'destroy'
]);
// 使用路由名称生成 URL
$url = route('profile', ['id' => 1]);
// 生成重定向...
return redirect()->route('profile');
// 路由组前缀
Route::prefix('admin')->group(function () {
Route::get('/users', function () {
// Matches The "/admin/users" URL
});
});
// 路由模型绑定
use App\Models\User;
Route::get('/users/{user}', function (User $user) {
return $user->email;
});
// 路由模型绑定(id 除外)
use App\Models\User;
Route::get('/posts/{post:slug}', function (Post $post) {
return view('post', ['post' => $post]);
});
// 备选路由
Route::fallback(function () {
//
});缓存
// 路由缓存
php artisan route:cache
// 获取或保存(键,存活时间,值)
$users = Cache::remember('users', now()->addMinutes(5), function () {
return DB::table('users')->get();
});控制器
// 设置校验规则
protected $rules = [
'title' => 'required|unique:posts|max:255',
'name' => 'required|min:6',
'email' => 'required|email',
'publish_at' => 'nullable|date',
];
// 校验
$validatedData = $request->validate($rules)
// 显示 404 错误页
abort(404, 'Sorry, Post not found')
// Controller CRUD 示例
Class ProductsController
{
public function index()
{
$products = Product::all();
// app/resources/views/products/index.blade.php
return view('products.index', ['products', $products]);
}
public function create()
{
return view('products.create');
}
public function store()
{
Product::create(request()->validate([
'name' => 'required',
'price' => 'required',
'note' => 'nullable'
]));
return redirect(route('products.index'));
}
// 模型注入方法
public function show(Product $product)
{
return view('products.show', ['product', $product]);
}
public function edit(Product $product)
{
return view('products.edit', ['product', $product]);
}
public function update(Product $product)
{
Product::update(request()->validate([
'name' => 'required',
'price' => 'required',
'note' => 'nullable'
]));
return redirect(route($product->path()));
}
public function delete(Product $product)
{
$product->delete();
return redirect("/contacts");
}
}
// 获取 Query Params www.demo.html?name=mike
request()->name //mike
// 获取 Form data 传参(或默认值)
request()->input('email', 'no@email.com')Template
@yield('content')
@extends('layout')
@section('content') … @endsection
@include('view.name', ['name' => 'John'])
{{ var_name }}
{ !! var_name !! }
@foreach ($items as $item)
{{ $item.name }}
@if($loop->last)
$loop->index
@endif
@endforeach
@if ($post->id === 1)
'Post one'
@elseif ($post->id === 2)
'Post two!'
@else
'Other'
@endif