新鮮出爐的Laravel 速查表不要錯過!

下面由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/Faker

Seed

// 例子: 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 = AppFlight::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 AppHttpControllersUserController; 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 AppModelsUser; Route::get('/users/{user}', function (User $user) {     return $user->email; });  // 路由模型綁定(id 除外) use AppModelsUser; 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

<!-- 路由名 --> <a href="{{ route('routeName.show', $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('posts.store') }}">  @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('title') is-invalid @enderror">  <!-- 上一次請求數據填充表單 --> {{ old('name') }}

不使用模型訪問數據庫

use IlluminateSupportFacadesDB; $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');

幫助函數

// 顯示變量內容并終止執行 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();

閃存 和 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

HTTP Client

// 引入包 use IlluminateSupportFacadesHttp;  // 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']);

Storage (用于存儲在本地文件或者云端服務的助手類)

// 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 IlluminateSupportFacadesStorage; Storage::disk('public')->put('example.txt', 'Contents'); $contents = Storage::disk('public')->get('file.jpg');   // 通過生成訪問資源的 url  $url = Storage::url('file.jpg'); // 或者通過公共配置的絕對路徑 @@##@@  // 刪除文件 Storage::delete('file.jpg');  // 下載文件 Storage::disk('public')->download('export.csv');

從 github 安裝新項目

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

Heroku 部署

// 本地(MacOs)機器安裝 Heroku  $ brew tap heroku/brew && brew install heroku  // 登陸 heroku (不存在則創建) $ heroku login  // 創建 Profile  $ touch Profile  // 保存 Profile web: vendor/bin/heroku-php-apache2 public/

Rest API (創建 Rest API 端點)

API 路由 ( 所有 api 路由都帶 ‘api/’ 前綴 )

// routes/api.php Route::get('products', [AppHttpControllersProductsController::class, 'index']); Route::get('products/{product}', [AppHttpControllersProductsController::class, 'show']); Route::post('products', [AppHttpControllersProductsController::class, 'store']);

API 資源 (介于模型和 JSON 響應之間的資源層)

$ php artisan make:resource ProductResource

資源路由定義文件

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

API 控制器 (最佳實踐是將您的 API 控制器放在 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);     }

API 令牌認證

首先,您需要為特定用戶創建一個 Token?!鞠嚓P推薦:laravel

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

然后可以一個請求使用這個令牌

GET api/products (Auth Bearer Token: plainTextToken)

授權規則
您可以使用預定義的授權規則創建令牌

$user->createToken('dev token', ['product-list']);  // in controllers if !auth()->user()->tokenCan('product-list') {     abort(403, "Unauthorized"); }

原文地址:https://dev.to/ericchapman/my-beloved-laravel-cheat-sheet-3l73

譯文地址:https://learnku.com/laravel/t/62150

新鮮出爐的Laravel 速查表不要錯過!

? 版權聲明
THE END
喜歡就支持一下吧
點贊7 分享