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
變數
在blade
的foreach
中,即使在兩個循環中,依然可以透過使用$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()
中指定列
當你使用Eloqument
的Model::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
的特定檢查
在Eloquent
的hasMany()
關係中,你可以篩選出具有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中文網其他相關文章!

Laravel通過簡化Web開發過程和提供強大功能脫穎而出。其優勢包括:1)簡潔的語法和強大的ORM系統,2)高效的路由和認證系統,3)豐富的第三方庫支持,使得開發者能專注於編寫優雅的代碼並提高開發效率。

laravelispredminandermanthandermanthandermanthandermanthermanderframework,設計Forserver-SideLogic,databasemagement,andapideplupment,thryitalsosupportsfortfortsfrontenddevelopmentwithbladeTemplates。

Laravel和Python在性能和可擴展性方面的表現各有優劣。 Laravel通過異步處理和隊列系統提升性能,但受PHP限制在高並發時可能有瓶頸;Python利用異步框架和強大的庫生態系統表現出色,但在多線程環境下受GIL影響。

Laravel適合團隊熟悉PHP且需功能豐富的項目,Python框架則視項目需求而定。 1.Laravel提供優雅語法和豐富功能,適合需要快速開發和靈活性的項目。 2.Django適合複雜應用,因其“電池包含”理念。 3.Flask適用於快速原型和小型項目,提供極大靈活性。

Laravel可以用於前端開發。 1)使用Blade模板引擎生成HTML。 2)集成Vite管理前端資源。 3)構建SPA、PWA或靜態網站。 4)結合路由、中間件和EloquentORM創建完整Web應用。

PHP和Laravel可用於構建高效的服務器端應用。 1.PHP是開源腳本語言,適用於Web開發。 2.Laravel提供路由、控制器、EloquentORM、Blade模板引擎等功能,簡化開發。 3.通過緩存、代碼優化和安全措施,提升應用性能和安全性。 4.測試和部署策略確保應用穩定運行。

Laravel和Python在學習曲線和易用性上的表現各有優劣。 Laravel適合快速開發Web應用,學習曲線相對平緩,但掌握高級功能需時間;Python語法簡潔,學習曲線平緩,但動態類型系統需謹慎。

Laravel在後端開發中的優勢包括:1)優雅的語法和EloquentORM簡化了開發流程;2)豐富的生態系統和活躍的社區支持;3)提高了開發效率和代碼質量。 Laravel的設計讓開發者能夠更高效地進行開發,並通過其強大的功能和工具提升代碼質量。


熱AI工具

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

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

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

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

熱門文章

熱工具

SublimeText3 Mac版
神級程式碼編輯軟體(SublimeText3)

Safe Exam Browser
Safe Exam Browser是一個安全的瀏覽器環境,安全地進行線上考試。該軟體將任何電腦變成一個安全的工作站。它控制對任何實用工具的訪問,並防止學生使用未經授權的資源。

Atom編輯器mac版下載
最受歡迎的的開源編輯器

EditPlus 中文破解版
體積小,語法高亮,不支援程式碼提示功能

SecLists
SecLists是最終安全測試人員的伙伴。它是一個包含各種類型清單的集合,這些清單在安全評估過程中經常使用,而且都在一個地方。 SecLists透過方便地提供安全測試人員可能需要的所有列表,幫助提高安全測試的效率和生產力。清單類型包括使用者名稱、密碼、URL、模糊測試有效載荷、敏感資料模式、Web shell等等。測試人員只需將此儲存庫拉到新的測試機上,他就可以存取所需的每種類型的清單。