Home > PHP Framework > Laravel > body text

Don't miss the freshly released Laravel cheat sheet!

藏色散人
Release: 2021-11-01 15:50:39
forward
2253 people have browsed it

The following tutorial column of Laravel will introduce you to the freshly released Laravel cheat sheet. I hope it will be helpful to everyone!


Laravel Cheat Sheet

Project Commands

// 创建新项目
$ laravel new projectName

// 运行 服务/项目
$ php artisan serve

// 查看指令列表
$ php artisan list

// 帮助
$ php artisan help migrate

// Laravel 控制台
$ php artisan tinker

// 查看路由列表
$ php artisan route:list
Copy after login

Public Commands

// 数据库迁移
$ 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
Copy after login

Create and Update Data Tables

// 创建数据表
$ 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');
});
Copy after login

Model

// 模型质量指定列表排除属性
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);
    }
Copy after login

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/Faker
Copy after login

Seed

// 例子: database/seeders/DatabaseSeeder.php
public function run() {
    Product::factory(10)->create();
}
Copy after login

Running Seeders

$ php artisan db:seed
// 或者 migration 时执行
$ php artisan migrate --seed
Copy after login

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'))
Copy after login

Routing

// 基础闭包路由
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 () {
    //
});
Copy after login

Cache

// 路由缓存
php artisan route:cache

// 获取或保存(键,存活时间,值)
$users = Cache::remember('users', now()->addMinutes(5), function () {
    return DB::table('users')->get();
});
Copy after login

Controller

// 设置校验规则
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')
Copy after login

Template

<!-- 路由名 -->
<a href="{{ route(&#39;routeName.show&#39;, $id) }}">

<!-- 模板继承 -->
@yield('content')  <!-- layout.blade.php -->
@extends('layout')
@section('content') … @endsection

<!-- 模板 include -->
@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

<!--Form 表单 -->
<form method="POST" action="{{ route(&#39;posts.store&#39;) }}">

@method(‘PUT’)
@csrf

<!-- Request 路径匹配 -->
{{ request()->is('posts*') ? 'current page' : 'not current page' }} 

<!-- 路由是否存在 -->
@if (Route::has('login'))

<!-- Auth blade 变量 -->
@auth 
@endauth 
@guest

<!-- 当前用户 -->
{{ Auth::user()->name }}

<!-- Validations 验证错误 -->
@if ($errors->any())
    <p class="alert alert-danger">
        <ul>
            @foreach ($errors->all() as $error)
                <li>{{ $error }}</li>
            @endforeach
        </ul>
    </p>
@endif

<!-- 检查具体属性 -->
<input id="title" type="text" class="@error(&#39;title&#39;) is-invalid @enderror">

<!-- 上一次请求数据填充表单 -->
{{ old('name') }}
Copy after login

Accessing the database without using a model

use Illuminate\Support\Facades\DB;
$user = DB::table('users')->first();
$users = DB::select('select name, email from users');
DB::insert('insert into users (name, email, password) value(?, ?, ?)', ['Mike', 'mike@hey.com', 'pass123']);
DB::update('update users set name = ? where id = 1', ['eric']);
DB::delete('delete from users where id = 1');
Copy after login

Helper function

// 显示变量内容并终止执行
dd($products)

// 将数组转为Laravel集合
$collection = collect($array);

// 按描述升序排序
$ordered_collection = $collection->orderBy(‘description’);

// 重置集合键
$ordered_collection = $ordered_collection->values()->all();

// 返回项目完整路径
app\ : app_path();
resources\ : resource_path();
database\ :database_path();
Copy after login

Flash and Session

// 闪存(只有下一个请求)
$request->session()->flash('status', 'Task was successful!');

// 带重定向的闪存
return redirect('/home')->with('success' => 'email sent!');

// 设置 Session
$request->session()->put('key', 'value');

// 获取 session
$value = session('key');
If session: if ($request->session()->has('users'))

// 删除 session
$request->session()->forget('key');

// 在模板中显示 flash
@if (session('message')) {{ session('message') }} @endif
Copy after login

HTTP Client

// 引入包
use Illuminate\Support\Facades\Http;

// Http get 方式请求
$response = Http::get('www.thecat.com')
$data = $response->json()

// Http get 带参方式请求
$res = Http::get('www.thecat.com', ['param1', 'param2'])

// Http post 带请求体方式请求
$res = Http::post('http://test.com', ['name' => 'Steve','role' => 'Admin']);

// 带令牌认证方式请求
$res = Http::withToken('123456789')->post('http://the.com', ['name' => 'Steve']);

// 带请求头方式发起请求
$res = Http::withHeaders(['type'=>'json'])->post('http://the.com', ['name' => 'Steve']);
Copy after login

Storage (helper class for storage in local files or cloud services)

// Public 驱动配置: Local storage/app/public
Storage::disk('public')->exists('file.jpg')) 
// S3 云存储驱动配置: storage: 例如 亚马逊云:
Storage::disk('s3')->exists('file.jpg')) 

// 在 web 服务中暴露公共访问内容
php artisan storage:link

// 在存储文件夹中获取或者保存文件
use Illuminate\Support\Facades\Storage;
Storage::disk('public')->put('example.txt', 'Contents');
$contents = Storage::disk('public')->get('file.jpg'); 

// 通过生成访问资源的 url 
$url = Storage::url('file.jpg');
// 或者通过公共配置的绝对路径
<img src={{ asset(&#39;storage/image1.jpg&#39;) }}/>

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

// 下载文件
Storage::disk('public')->download('export.csv');
Copy after login

Install new projects from github

$ git clone {project http address} projectName
$ cd projectName
$ composer install
$ cp .env.example .env
$ php artisan key:generate
$ php artisan migrate
$ npm install
Copy after login

Heroku Deployment

// 本地(MacOs)机器安装 Heroku 
$ brew tap heroku/brew && brew install heroku

// 登陆 heroku (不存在则创建)
$ heroku login

// 创建 Profile 
$ touch Profile

// 保存 Profile
web: vendor/bin/heroku-php-apache2 public/
Copy after login

Rest API (Create Rest API endpoint)

API routing (all api routes are prefixed with 'api/')

// routes/api.php
Route::get('products', [App\Http\Controllers\ProductsController::class, 'index']);
Route::get('products/{product}', [App\Http\Controllers\ProductsController::class, 'show']);
Route::post('products', [App\Http\Controllers\ProductsController::class, 'store']);
Copy after login

API resources (The resource layer between the model and the JSON response)

$ php artisan make:resource ProductResource
Copy after login

Resource route definition file

// app/resource/ProductResource.php
public function toArray($request)
    {
        return [
            'id' => $this->id,
            'name' => $this->name,
            'price' => $this->price,
            'custom' => 'This is a custom field',
        ];
    }
Copy after login

API controller (best practice is to place your API controller in app/Http /Controllers/API/v1/中)

public function index() {
        //$products = Product::all();
        $products = Product::paginate(5);
        return ProductResource::collection($products);
    }

    public function show(Product $product) {
        return new ProductResource($product);
    }

    public function store(StoreProductRequest $request) {
        $product = Product::create($request->all());
        return new ProductResource($product);
    }
Copy after login

API Token Authentication

First, you need to create a Token for a specific user. [Related recommendations: The latest five Laravel video tutorials]

$user = User::first();
$user->createToken('dev token');
// plainTextToken: "1|v39On3Uvwl0yA4vex0f9SgOk3pVdLECDk4Edi4OJ"
Copy after login

Then you can use this token with one request

GET api/products (Auth Bearer Token: plainTextToken)
Copy after login

Authorization rules
You can use predefined Authorization rules to create tokens

$user->createToken('dev token', ['product-list']);

// in controllers
if !auth()->user()->tokenCan('product-list') {
    abort(403, "Unauthorized");
}
Copy after login

Original address: https://dev.to/ericchapman/my-beloved-laravel-cheat-sheet-3l73

Translation address: https ://learnku.com/laravel/t/62150

The above is the detailed content of Don't miss the freshly released Laravel cheat sheet!. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:learnku.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!