使用Laravel時的一些小技巧

使用Laravel時的一些小技巧

01: 觸發(fā)父級的時間戳

如標題所示,在子模型更新時,可以觸發(fā)父模型的時間戳。例如 Comment 屬于 Post,有時更新子模型導致更新父模型時間戳非常有用。例如,當 Comment 模型被更新時,您要自動觸發(fā)父級 Post 模型的 updated_at 時間戳的更新。Eloquent 讓它變得簡單,只需添加一個包含子模型關系名稱的 touch 屬性。

<?php namespace App; use IlluminateDatabaseEloquentModel; class Comment extends Model {     /**      * 涉及到的所有關聯(lián)關系。      *      * @var array      */     protected $touches = ['post'];     /**      * 獲取評論所屬的文章。      */     public function post()     {         return $this->belongsTo('AppPost');     } }

02: 預加載精確的列

在使用預加載時,可以從關系中獲取指定的列。

$users = AppBook::with('author:id,name')->get();

03: 為單個請求驗證用戶身份

你可以使用 Auth::once() 來為單個請求驗證用戶的身份,此方法不會使用 Cookie 會話。這意味著此方法可能有助于構建無狀態(tài) API

if (Auth::once($credentials)) {     // }

04: 重定向到帶有參數(shù)的控制器方法中

你不僅可以將 redirect() 方法用于用戶特定的 URL 或者路由中,還可以用于控制器中帶有參數(shù)的方法中。

return redirect()->action('SomeController@method', ['param' => $value]);

05: 如何使用 withDefault() 避免在關系中出現(xiàn)的錯誤

當一個關系被調(diào)用時,如果它不存在,則會出現(xiàn)致命的錯誤,例如 $post->user->name ,可以使用 withDefault() 來避免。

/** 獲取文章作者 */  public function user()  {          return $this->belongsTo('AppUser')->withDefault();  }

06: 在模版中兩個平級的 $loop 變量

在 blade 的 foreach 中,即使在兩次循環(huán)中,依然可以通過使用 $loop 變量來獲取父級變量。

@foreach ($users as $user)          @foreach ($user->posts as $post)                  @if ($loop->parent->first)                          This is first iteration of the parent loop.                  @endif          @endforeach  @endforeach

07: 修改查詢結果

在執(zhí)行 Eloqument 查詢后,你可以使用 map() 來修改行。

$users = User::where('role_id', 1)->get()->map(function (User $user) {     $user->some_column = some_function($user);     return $user; });

08: 輕松的使用 dd()

在 Eloqument 的最后加上 $test->dd(),來代替 dd($result)。

// 優(yōu)化前 $users = User::where('name', 'Taylor')->get(); dd($users); // 優(yōu)化后 $users = User::where('name', 'Taylor')->get()->dd();

09: Use hasMany to saveMany.

如果有 hasMany() 關聯(lián)關系,和想要從父類對象中保存許多子類對象,可以使用 saveMany() 來達到你想要的效果。

$post = Post::find(1); $post->comments()->saveMany([     new Comment(['message' => 'First comment']),     new Comment(['message' => 'Second comment']), ]);

10: 在 Model::all() 中指定列

當你使用 Eloqument 的 Model::all() 時,你可以指定要返回的列。

$users = User::all(['id', 'name', 'email']);

11: Blade 中的 @auth

你可以使用 @auth 指令來代替 if 語句來檢查用戶是否經(jīng)過身份驗證。

典型的方法:
@if(auth()->user())     // The user is authenticated. @endif
簡短的方法:
@auth      // The user is authenticated.  @endauth

12: 預覽郵件而不發(fā)送

如果你使用 Mailables 來發(fā)送你的郵件,你可以預覽它們而不發(fā)送出去。

Route::get('/mailable', function () {     $invoice = AppInvoice::find(1);     return new AppMailInvoicePaid($invoice); });

13: hasMany 的特定檢查

在 Eloquent 的 hasMany() 關系中,你可以篩選出具有 n 個子記錄數(shù)量的記錄。

// Author -> hasMany(Book::class)  $authors = Author::has('books', '>', 5)->get();

14: 恢復多個軟刪除

如果記錄使用了軟刪除,那么你就可以一次恢復多條軟刪除記錄。

Post::withTrashed()->where('author_id', 1)->restore();

15: 帶時區(qū)的遷移列

遷移文件不僅有 timestamps() 時間戳,還有 timestampsTz() 帶有時區(qū)的時間戳。

Schema::create('employees', function (Blueprint $table) {     $table->increments('id');     $table->string('name');     $table->string('email');     $table->timestampsTz(); });

16: 視圖文件是否存在?

你知道還可以檢查視圖文件是否存在嗎?

if (view()->exists('custom.page')) {     // Load the view }

17: 組中的路由組

在路由文件中,你可以為一個路由組創(chuàng)造一個組,還可以為其指定特定的中間件

Route::group(['prefix' => 'account', 'as' => 'account.'], function() {     Route::get('login', 'AccountController@login');          Route::get('register', 'AccountController@register');     Route::group(['middleware' => 'auth'], function() {                  Route::get('edit', 'AccountController@edit');          }); });

18: Eloquent 中的日期時間方法

whereDay() , whereMonth() , whereYear() , whereDate() , whereTime() 這些方法皆為 Eloquent 中檢查日期的方法。

$products = Product::whereDate('created_at', '2018-01-31')->get();  $products = Product::whereMonth('created_at', '12')->get();  $products = Product::whereDay('created_at', '31')->get();  $products = Product::whereYear('created_at', date('Y'))->get();  $products = Product::whereTime('created_at', '=', '14:13:58')->get();

19: 在 Eloquent 關系中使用 orderBy()

你可以在 Eloquent 關系中直接指定 orderBy() 。

public function products() {     return $this->hasMany(Product::class); } public function productsByName() {     return $this->hasMany(Product::class)->orderBy('name'); }

20: 無符號整型

對于遷移的外鍵,不要使用 Integer() , 而是使用 unsignedInteger() 或者是 integer()->unsigned() ,否則將會出現(xiàn)一系列的錯誤。

Schema::create('employees', function (Blueprint $table) {          $table->unsignedInteger('company_id');          $table->foreign('company_id')->references('id')->on('companies');      });

更多laravel相關技術文章,請訪問Laravel教程欄目進行學習!

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