搜尋
首頁php框架Laravel使用Laravel時的一些小技巧

使用Laravel時的一些小技巧

Jun 28, 2019 pm 04:12 PM
laravel

使用Laravel時的一些小技巧

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 = [&#39;post&#39;];
    /**
     * 获取评论所属的文章。
     */
    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');     
});

更多Laravel相關技術文章,請造訪Laravel教學專欄進行學習!

以上是使用Laravel時的一些小技巧的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
最新的Laravel版本:DIFES DISCON最新的Laravel版本:DIFES DISCONMay 12, 2025 am 12:15 AM

Laravel10IntroducessEveralKeyFeatUrestHatenHanceWebDevelopment.1)LazyCollectionsAllyCollefficeProcesingOflargeFlargedAtasetSwithSwithOutloadingAllRecordSintomeMemory.2)the Make:Model Model Moged-and-Mogration'ArtisanCommandSancancMommandSimplififieScreatingModeltigation.3)

Laravel遷移解釋了:創建,修改和管理您的數據庫Laravel遷移解釋了:創建,修改和管理您的數據庫May 12, 2025 am 12:11 AM

laravelmigrationssshouldbeusedbecausetheystreamlinedeplupment,nesurecresistencyAcrossenviments和simplifyCollaborationAndDeployment.1)shemallogragrammatonofdatabaseschemachanges,ReeducingErrors.2)MigrigationScanBeverCanbeverSionConconconconcontrollin.2)

Laravel遷移:值得使用嗎?Laravel遷移:值得使用嗎?May 12, 2025 am 12:10 AM

是的。

Laravel:軟刪除了性能問題Laravel:軟刪除了性能問題May 12, 2025 am 12:04 AM

SoftDeletesinLaravelimpactperformancebycomplicatingqueriesandincreasingstorageneeds.Tomitigatetheseissues:1)Indexthedeleted_atcolumntospeedupqueries,2)Useeagerloadingtoreducequerycount,and3)Regularlycleanupsoft-deletedrecordstomaintaindatabaseefficie

Laravel遷移對什麼有益?用例和福利Laravel遷移對什麼有益?用例和福利May 11, 2025 am 12:14 AM

Laravelmigrationsarebeneficialforversioncontrol,collaboration,andpromotinggooddevelopmentpractices.1)Theyallowtrackingandrollingbackdatabasechanges.2)Migrationsensureteammembers'schemasstaysynchronized.3)Theyencouragethoughtfuldatabasedesignandeasyre

如何在Laravel中使用軟刪除:保護您的數據如何在Laravel中使用軟刪除:保護您的數據May 11, 2025 am 12:14 AM

Laravel的軟刪除功能通過標記記錄而非實際刪除來保護數據。 1)在模型中添加SoftDeletestrait和deleted_at字段。 2)使用delete()方法標記刪除,使用restore()方法恢復。 3)查詢時使用withTrashed()或onlyTrashed()包含軟刪除記錄。 4)定期清理超過一定時間的軟刪除記錄以優化性能。

Laravel遷移是什麼,您如何使用它們?Laravel遷移是什麼,您如何使用它們?May 11, 2025 am 12:13 AM

laravelmigrationSareversionControlfordatabaseschemas,允許Roducibleandreversiblechanges.tousethem:1)creatighatsanmake:遷移',2)定義chemachangesinthe'up()

Laravel遷移:回滾行不通,發生了什麼事?Laravel遷移:回滾行不通,發生了什麼事?May 11, 2025 am 12:10 AM

Laravelmigrationsmayfailtorollbackduetodataintegrityissues,foreignkeyconstraints,orirreversibleactions.1)Dataintegrityissuescanoccurifamigrationaddsdatathatcan'tbeundone,likeacolumnwithadefaultvalue.2)Foreignkeyconstraintscanpreventrollbacksifrelatio

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

SublimeText3 Linux新版

SublimeText3 Linux新版

SublimeText3 Linux最新版

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

強大的PHP整合開發環境

EditPlus 中文破解版

EditPlus 中文破解版

體積小,語法高亮,不支援程式碼提示功能

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

將Eclipse與SAP NetWeaver應用伺服器整合。

MantisBT

MantisBT

Mantis是一個易於部署的基於Web的缺陷追蹤工具,用於幫助產品缺陷追蹤。它需要PHP、MySQL和一個Web伺服器。請查看我們的演示和託管服務。