Laravel路由組件:簡化高效的路由管理
本文探討Laravel強大的路由組件,它提供簡潔高效的路由管理方式,支持簡潔的URL、參數、分組、命名以及路由組的事件保護等特性。其路由模型綁定功能通過類型提示模型名稱而非ID參數,簡化了重複性任務的處理。
核心要點:
- Laravel的路由組件提供簡單高效的路由管理方式,支持簡潔URL、參數、分組、命名以及事件保護路由組等功能。路由模型綁定功能通過類型提示模型名稱而非ID參數,簡化了重複性任務處理。
- Laravel的路由模型綁定會自動使用ID參數解析模型,如果模型不存在則拋出異常。
App\Exceptions\Handler@render
方法負責將異常轉換為HTTP響應,可用於處理ModelNotFoundException
並重定向到404頁面。 - Laravel允許自定義路由模型綁定,例如重寫父模型類的
getRouteKeyName
方法來使用不同的屬性名稱,比如UUID。這有助於避免將內部ID暴露給最終用戶。
示例:管理後台類別
假設數據庫中有一系列類別,管理員可在後台管理這些類別。路由文件如下:
Route::group(['namespace' => 'Admin', 'prefix' => 'admin', 'middleware' => 'admin'], function () { Route::resource('categories', 'CategoriesController'); });
CategoriesController
類包含七個資源方法。在edit
操作中,需要檢查待編輯的類別是否存在於數據庫中,否則返回錯誤消息並重定向:
public function edit($id) { $category = Category::find($id); if (!$category) { return redirect()->route('admin.categories.index')->withErrors([trans('errors.category_not_found')]); } // ... }
路由模型綁定
這是常規做法,但Laravel提供了一種更優化的方式——路由模型綁定。只需類型提示模型名稱即可,無需ID參數。
可用路由列表如下:
<code>+--------+-----------+------------------------------------+------------------------------------+----------------------------------------------------------------------+-----------------+ | Domain | Method | URI | Name | Action | Middleware | +--------+-----------+------------------------------------+------------------------------------+----------------------------------------------------------------------+-----------------+ | | GET|HEAD | admin/categories | admin.categories.index | App\Http\Controllers\Admin\CategoriesController@index | web,admin | | | POST | admin/categories | admin.categories.store | App\Http\Controllers\Admin\CategoriesController@store | web,admin | | | GET|HEAD | admin/categories/create | admin.categories.create | App\Http\Controllers\Admin\CategoriesController@create | web,admin | | | GET|HEAD | admin/categories/{categories} | admin.categories.show | App\Http\Controllers\Admin\CategoriesController@show | web,admin | | | PUT|PATCH | admin/categories/{categories} | admin.categories.update | App\Http\Controllers\Admin\CategoriesController@update | web,admin | | | DELETE | admin/categories/{categories} | admin.categories.destroy | App\Http\Controllers\Admin\CategoriesController@destroy | web,admin | | | GET|HEAD | admin/categories/{categories}/edit | admin.categories.edit | App\Http\Controllers\Admin\CategoriesController@edit | web,admin |</code>
路由參數為 {categories}
,可根據需要修改。 Laravel提供了一個修改它的選項:
Route::resource('categories', 'CategoriesController', [ 'parameters' => 'singular', ]);
修改後的路由:
<code>+--------+-----------+------------------------------------+------------------------------------+----------------------------------------------------------------------+-----------------+ | Domain | Method | URI | Name | Action | Middleware | +--------+-----------+------------------------------------+------------------------------------+----------------------------------------------------------------------+-----------------+ | | GET|HEAD | admin/categories | admin.categories.index | App\Http\Controllers\Admin\CategoriesController@index | web,admin | | | POST | admin/categories | admin.categories.store | App\Http\Controllers\Admin\CategoriesController@store | web,admin | | | GET|HEAD | admin/categories/create | admin.categories.create | App\Http\Controllers\Admin\CategoriesController@create | web,admin | | | GET|HEAD | admin/categories/{category} | admin.categories.show | App\Http\Controllers\Admin\CategoriesController@show | web,admin | | | PUT|PATCH | admin/categories/{category} | admin.categories.update | App\Http\Controllers\Admin\CategoriesController@update | web,admin | | | DELETE | admin/categories/{category} | admin.categories.destroy | App\Http\Controllers\Admin\CategoriesController@destroy | web,admin | | | GET|HEAD | admin/categories/{category}/edit | admin.categories.edit | App\Http\Controllers\Admin\CategoriesController@edit | web,admin |</code>
注意: Laravel 5.3 默認使用單數形式。
public function edit(Category $category) { return view('admin.categories.edit', [ 'category' => $category ]); }
現在,Laravel將自動使用ID參數解析類別,如果模型不存在則拋出異常。
注意: 除非參數有默認值,否則它使用 findOrFail
Eloquent 方法來解析參數。
異常處理
App\Exceptions\Handler@render
方法負責將異常轉換為HTTP響應。我們將使用它來處理 ModelNotFoundException
並重定向到404頁面。
該方法具有 request
和 exception
參數,可用於確定要執行的操作。
Route::group(['namespace' => 'Admin', 'prefix' => 'admin', 'middleware' => 'admin'], function () { Route::resource('categories', 'CategoriesController'); });
我們測試拋出的異常是否為 ModelNotFoundException
的實例。我們還可以測試模型名稱以顯示正確的錯誤消息。為了避免為所有模型添加多個 if
測試,我們可以創建一個索引消息數組,並使用模型類名來提取正確的消息。
參數解析
Laravel 使用名稱和類型提示來解析路由參數。如果參數類型是模型,則它嘗試使用 ID 在數據庫中查找記錄,如果找不到記錄則失敗。
自定義路由鍵
為避免將內部ID暴露給最終用戶,通常使用UUID。但由於Laravel使用表主鍵來解析綁定參數,因此始終會拋出錯誤!
為此,Laravel允許我們重寫父模型類的getRouteKeyName
方法。該方法應返回屬性名稱,在本例中為UUID。
public function edit($id) { $category = Category::find($id); if (!$category) { return redirect()->route('admin.categories.index')->withErrors([trans('errors.category_not_found')]); } // ... }
現在,如果我們嘗試使用UUID編輯特定類別,它應該按預期工作,例如:https://www.php.cn/link/604541b9b9f266538ed001ea49fcc956。
Laravel路由模型綁定的常見問題解答 (這部分內容已在原文中詳細解答,此處不再贅述)
希望以上內容對您有所幫助!
以上是Laravel快速提示:模型路線綁定的詳細內容。更多資訊請關注PHP中文網其他相關文章!

TheSecretTokeEpingAphp-PowerEdwebSiterUnningSmoothlyShyunderHeavyLoadInVolvOLVOLVOLDEVERSALKEYSTRATICES:1)emplactopCodeCachingWithOpcachingWithOpCacheToreCescriptexecution Time,2)使用atabasequercachingCachingCachingWithRedataBasEndataBaseLeSendataBaseLoad,3)

你應該關心DependencyInjection(DI),因為它能讓你的代碼更清晰、更易維護。 1)DI通過解耦類,使其更模塊化,2)提高了測試的便捷性和代碼的靈活性,3)使用DI容器可以管理複雜的依賴關係,但要注意性能影響和循環依賴問題,4)最佳實踐是依賴於抽象接口,實現鬆散耦合。

是的,優化papplicationispossibleandessential.1)empartcachingingcachingusedapcutorediucedsatabaseload.2)優化的atabaseswithexing,高效Quereteries,and ConconnectionPooling.3)EnhanceCodeWithBuilt-unctions,避免使用,避免使用ingglobalalairaiables,並避免使用

theKeyStrategiestosigantificallyBoostPhpaPplicationPerformenCeare:1)UseOpCodeCachingLikeLikeLikeLikeLikeCacheToreDuceExecutiontime,2)優化AtabaseInteractionswithPreparedStateTementStatementStatementAndProperIndexing,3)配置

aphpdepentioncontiveContainerIsatoolThatManagesClassDeptions,增強codemodocultion,可驗證性和Maintainability.itactsasaceCentralHubForeatingingIndections,因此reducingTightCightTightCoupOulplingIndeSingantInting。

選擇DependencyInjection(DI)用於大型應用,ServiceLocator適合小型項目或原型。 1)DI通過構造函數注入依賴,提高代碼的測試性和模塊化。 2)ServiceLocator通過中心註冊獲取服務,方便但可能導致代碼耦合度增加。

phpapplicationscanbeoptimizedForsPeedAndeffificeby:1)啟用cacheInphp.ini,2)使用preparedStatatementSwithPdoforDatabasequesies,3)3)替換loopswitharray_filtaray_filteraray_maparray_mapfordataprocrocessing,4)conformentnginxasaseproxy,5)

phpemailvalidation invoLvesthreesteps:1)格式化進行regulareXpressecthemailFormat; 2)dnsvalidationtoshethedomainhasavalidmxrecord; 3)


熱AI工具

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

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

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

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

熱門文章

熱工具

SublimeText3 Linux新版
SublimeText3 Linux最新版

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

ZendStudio 13.5.1 Mac
強大的PHP整合開發環境

DVWA
Damn Vulnerable Web App (DVWA) 是一個PHP/MySQL的Web應用程序,非常容易受到攻擊。它的主要目標是成為安全專業人員在合法環境中測試自己的技能和工具的輔助工具,幫助Web開發人員更好地理解保護網路應用程式的過程,並幫助教師/學生在課堂環境中教授/學習Web應用程式安全性。 DVWA的目標是透過簡單直接的介面練習一些最常見的Web漏洞,難度各不相同。請注意,該軟體中

記事本++7.3.1
好用且免費的程式碼編輯器