亚洲国产日韩欧美一区二区三区,精品亚洲国产成人av在线,国产99视频精品免视看7,99国产精品久久久久久久成人热,欧美日韩亚洲国产综合乱

目錄
2. Define the Resource Structure
3. Use the Resource in a Controller
4. Working with Relationships (Nested Resources)
5. Conditional Attributes
6. Customize the Top-Level Response (Resource Collection)
首頁 php框架 Laravel 如何在Laravel中使用API資源?

如何在Laravel中使用API資源?

Jul 27, 2025 am 04:09 AM

使用API資源是Laravel中構(gòu)建RESTful API時返回結(jié)構(gòu)化JSON響應的推薦方式。 1. 使用php artisan make:resource PostResource創(chuàng)建資源類;2. 在toArray方法中定義返回字段,如id、title、created_at等;3. 在控制器中返回new PostResource($post)或PostResource::collection($posts);4. 通過new UserResource($this->whenLoaded('user'))處理嵌套關(guān)係;5. 使用$this->when()條件包含字段,避免返回null;6. 通過additional()方法添加元數(shù)據(jù),如分頁信息;7. 遵循最佳實踐,包括預加載關(guān)係、避免N 1查詢、保持資源邏輯簡潔。通過這種方式,Laravel能自動生成一致且可維護的JSON響應,提升API的可讀性和性能,最終實現(xiàn)高效的數(shù)據(jù)輸出。

How to use API resources in Laravel?

Using API resources in Laravel is a clean and efficient way to transform your models and collections into JSON responses, especially when building RESTful APIs. Laravel's API resources help you control exactly what data is returned and how it's structured, making your responses consistent and maintainable.

How to use API resources in Laravel?

Here's how to use API resources in Laravel:


1. Create an API Resource

First, generate a resource using Artisan. For a Post model, run:

How to use API resources in Laravel?
 php artisan make:resource PostResource

This creates a PostResource class in the app/Http/Resources directory.

If you're working with a collection (eg, list of posts), Laravel also provides a way to handle that automatically.

How to use API resources in Laravel?

You can also create a resource collection:

 php artisan make:resource PostCollection

But as of Laravel 8 , ResourceCollection is built into the base resource, so you usually just need one resource class.


2. Define the Resource Structure

Open app/Http/Resources/PostResource.php . The toArray method defines what data is included in the response.

 <?php

namespace App\Http\Resources;

use Illuminate\Http\Resources\Json\JsonResource;

class PostResource extends JsonResource
{
    public function toArray($request)
    {
        return [
            &#39;id&#39; => $this->id,
            &#39;title&#39; => $this->title,
            &#39;content&#39; => $this->content,
            &#39;created_at&#39; => $this->created_at->format(&#39;Ymd H:i:s&#39;),
            &#39;author&#39; => $this->whenLoaded(&#39;user&#39;, function () {
                return new UserResource($this->user);
            }),
        ];
    }
}

? Use $this->whenLoaded() to conditionally include relationships only if they're already loaded (to avoid N 1 queries).


3. Use the Resource in a Controller

In your controller, wrap the model or collection with the resource:

 use App\Http\Resources\PostResource;
use App\Models\Post;

// Return a single post
public function show(Post $post)
{
    return new PostResource($post);
}

// Return a list of posts
public function index()
{
    return PostResource::collection(Post::with(&#39;user&#39;)->get());
}

Or with pagination (common in APIs):

 public function index()
{
    return PostResource::collection(Post::paginate(10));
}

Laravel automatically handles the pagination structure.


4. Working with Relationships (Nested Resources)

If your post has a user, create a UserResource :

 php artisan make:resource UserResource

Then use it inside PostResource :

 &#39;author&#39; => new UserResource($this->whenLoaded(&#39;user&#39;)),

This keeps your response structured and reusable.


5. Conditional Attributes

Use when() to include fields conditionally:

 &#39;published_at&#39; => $this->when(!empty($this->published_at), $this->published_at),
&#39;views&#39; => $this->when($this->resource->relationLoaded(&#39;stats&#39;), $this->views),

This avoids sending null values when data isn't relevant.


6. Customize the Top-Level Response (Resource Collection)

If you want to customize the wrapper (eg, add meta data), override the toResponse method or use an anonymous resource collection.

For example, in a controller:

 use Illuminate\Http\Resources\Json\AnonymousResourceCollection;

public function index(): AnonymousResourceCollection
{
    $posts = Post::paginate(10);

    return PostResource::collection($posts)->additional([
        &#39;meta&#39; => [
            &#39;total_pages&#39; => $posts->lastPage(),
            &#39;current_page&#39; => $posts->currentPage(),
        ],
    ]);
}

This adds extra info without creating a new resource class.


7. Best Practices

  • Always eager load relationships used in resources to avoid performance issues.
  • Use whenLoaded() for optional relationships.
  • Keep resource logic simple — don't put business logic inside.
  • Use different resources for different API versions if needed (eg, V1\PostResource ).

Using API resources in Laravel makes your API responses predictable and easy to maintain. You get full control over the output, and Laravel handles the JSON structure and status codes automatically.

Basically, wrap your models in resources, define the toArray() method, and return them from controllers — that's it.

以上是如何在Laravel中使用API資源?的詳細內(nèi)容。更多資訊請關(guān)注PHP中文網(wǎng)其他相關(guān)文章!

本網(wǎng)站聲明
本文內(nèi)容由網(wǎng)友自願投稿,版權(quán)歸原作者所有。本站不承擔相應的法律責任。如發(fā)現(xiàn)涉嫌抄襲或侵權(quán)的內(nèi)容,請聯(lián)絡admin@php.cn

熱AI工具

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅(qū)動的應用程序,用於創(chuàng)建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

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

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

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

熱工具

記事本++7.3.1

記事本++7.3.1

好用且免費的程式碼編輯器

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

禪工作室 13.0.1

禪工作室 13.0.1

強大的PHP整合開發(fā)環(huán)境

Dreamweaver CS6

Dreamweaver CS6

視覺化網(wǎng)頁開發(fā)工具

SublimeText3 Mac版

SublimeText3 Mac版

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

在Laravel項目中創(chuàng)建自定義驗證規(guī)則 在Laravel項目中創(chuàng)建自定義驗證規(guī)則 Jul 04, 2025 am 01:03 AM

在Laravel中添加自定義驗證規(guī)則的方法有三種:使用閉包、Rule類和表單請求。 1.使用閉包適合輕量級驗證,如阻止用戶名為"admin";2.創(chuàng)建Rule類(如ValidUsernameRule)使復雜邏輯更清晰可維護;3.在表單請求中整合多個規(guī)則並集中管理驗證邏輯,同時可通過自定義messages方法或傳入錯誤信息數(shù)組來設(shè)置提示語,從而提升靈活性和可維護性。

在Laravel應用程序中添加多語言支持 在Laravel應用程序中添加多語言支持 Jul 03, 2025 am 01:17 AM

Laravel應用實現(xiàn)多語言支持的核心方法包括:設(shè)置語言文件、動態(tài)切換語言、翻譯URL路由及管理Blade模板中的翻譯鍵。首先,將各語言字符串組織在/resources/lang目錄下的對應文件夾(如en、es、fr)中,並通過返回關(guān)聯(lián)數(shù)組定義翻譯內(nèi)容;2.通過\_\_()輔助函數(shù)調(diào)用翻譯鍵值,並使用App::setLocale()結(jié)合會話或路由參數(shù)實現(xiàn)語言切換;3.對於翻譯URL,可通過帶前綴的路由組分別為不同語言定義路徑,或動態(tài)映射語言文件中的路由別名;4.在Blade模板中保持翻譯鍵簡潔並

與Laravel中的樞軸表合作多對多關(guān)係 與Laravel中的樞軸表合作多對多關(guān)係 Jul 07, 2025 am 01:06 AM

toworkeffectivelywithpivottablesinlaravel,firstAccessPivotDatausingwithPivot()orwithTimestamps(),thenupdateentrieswithupdatee XistingPivot(),ManageraliationShipsviadeTach()andsync(),andusecustompivotModelSwhenNeed.1.UseWithPivot()toincludespecificcol

通過Laravel發(fā)送不同類型的通知 通過Laravel發(fā)送不同類型的通知 Jul 06, 2025 am 12:52 AM

laravelProvidesLeanAndFlexibleWayTosendificationsViamultiplipliplipliplikeMail,SMS,In-Appalerts,and-Appalerts,andPushNotifications.youdefineNotificationChannelsinthelsinthevia()MethodofanotificationClass,andimpecificementpecificementpecificementpecificemmethodssliketomail()

了解和創(chuàng)建Laravel的自定義服務提供商 了解和創(chuàng)建Laravel的自定義服務提供商 Jul 03, 2025 am 01:35 AM

ServiceProvider是Laravel框架中用於註冊服務和初始化邏輯的核心機制,通過Artisan命令可創(chuàng)建自定義ServiceProvider;1.register方法用於綁定服務、註冊單例、設(shè)置別名等操作,不可調(diào)用尚未加載的其他服務;2.boot方法在所有服務註冊完成後運行,用於註冊事件監(jiān)聽器、視圖合成器、中間件等依賴其他服務的邏輯;常見用途包括綁定接口與實現(xiàn)、註冊Facade、加載配置、註冊命令行指令和視圖組件;建議集中相關(guān)綁定於一個ServiceProvider中管理,並註意註冊

了解Laravel的依賴注入? 了解Laravel的依賴注入? Jul 05, 2025 am 02:01 AM

依賴注入在Laravel中通過服務容器自動處理類的依賴關(guān)係,無需手動new對象。其核心是構(gòu)造函數(shù)注入和方法注入,如控制器中自動傳入Request實例。 Laravel通過類型提示解析依賴,遞歸創(chuàng)建所需對象。綁定接口與實現(xiàn)可通過服務提供者使用bind方法,或singleton綁定單例。使用時需確保類型提示、避免構(gòu)造函數(shù)複雜化、謹慎使用上下文綁定,並理解自動解析規(guī)則。掌握這些可提升代碼靈活性與維護性。

在Laravel應用程序中處理異常和記錄錯誤 在Laravel應用程序中處理異常和記錄錯誤 Jul 02, 2025 pm 03:24 PM

在Laravel應用中處理異常和記錄錯誤的核心方法包括:1.利用App\Exceptions\Handler類集中管理未處理異常,通過report()方法記錄或通知異常信息,例如發(fā)送Slack通知;2.使用Monolog配置日誌系統(tǒng),在config/logging.php中設(shè)置日誌級別與輸出方式,並在生產(chǎn)環(huán)境中啟用error及以上級別日誌,同時可在report()中結(jié)合上下文手動記錄詳細異常信息;3.自定義render()方法以返回統(tǒng)一的JSON格式錯誤響應,提升API前後端協(xié)作效率。這些步驟確

優(yōu)化Laravel應用程序性能的策略 優(yōu)化Laravel應用程序性能的策略 Jul 09, 2025 am 03:00 AM

Laravel性能優(yōu)化可通過四個核心方向提升應用效率。 1.使用緩存機制減少重複查詢,通過Cache::remember()等方法存儲不常變化的數(shù)據(jù),降低數(shù)據(jù)庫訪問頻率;2.從模型到查詢語句進行數(shù)據(jù)庫優(yōu)化,避免N 1查詢、指定字段查詢、添加索引、分頁處理及讀寫分離,減少瓶頸;3.將耗時操作如郵件發(fā)送、文件導出放入隊列異步處理,利用Supervisor管理工作者並設(shè)置重試機制;4.合理使用中間件與服務提供者,避免複雜邏輯和不必要的初始化代碼,延遲加載服務以提升啟動效率。

See all articles