使用 Laravel 時的一些小技巧

sayhe110發表於2019-04-02

譯文地址
第一次翻譯文章,如有翻譯不好的地方還請大家指出,大家也可以直接看原文。

01: 觸發父級的時間戳

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

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

02: 預載入精確的列

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

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

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

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

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

04: 重定向到帶有引數的控制器方法中

你不僅可以將 redirect() 方法用於使用者特定的 URL 或者路由中,還可以用於控制器中帶有引數的方法中。

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

05: 如何使用 withDefault() 避免在關係中出現的錯誤

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

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

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

bladeforeach 中,即使在兩次迴圈中,依然可以通過使用 $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: 修改查詢結果

在執行 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)

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

09: Use hasMany to saveMany.

如果有 hasMany() 關聯關係,和想要從父類物件中儲存許多子類物件,可以使用 saveMany() 來達到你想要的效果。

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

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

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

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

11: Blade 中的 @auth

你可以使用 @auth 指令來代替 if 語句來檢查使用者是否經過身份驗證。

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

12: 預覽郵件而不傳送

如果你使用 Mailables 來傳送你的郵件,你可以預覽它們而不傳送出去。

Route::get('/mailable', function () {
    $invoice = App\Invoice::find(1);
    return new App\Mail\InvoicePaid($invoice);
});

13: hasMany 的特定檢查

EloquenthasMany() 關係中,你可以篩選出具有 n 個子記錄數量的記錄。

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

14: 恢復多個軟刪除

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

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

15: 帶時區的遷移列

遷移檔案不僅有 timestamps() 時間戳,還有 timestampsTz() 帶有時區的時間戳。

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: 組中的路由組

在路由檔案中,你可以為一個路由組創造一個組,還可以為其指定特定的中介軟體。

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() ,否則將會出現一系列的錯誤。

Schema::create('employees', function (Blueprint $table) {     
    $table->unsignedInteger('company_id');     
    $table->foreign('company_id')->references('id')->on('companies');     
});
本作品採用《CC 協議》,轉載必須註明作者和本文連結

相關文章