Skip to main content

Using Larave Api Resource , Adding Additional data to Response

 

Github repository for more styled code 

 https://github.com/MohamedFathiM/Blogs/blob/main/apiResource.md


What is the API Resource :

A transformation layer that sits between your Eloquent models and the JSON responses.

First Time Using It:

The first time I am using the API resource, I was confused about the difference between the two classes, you will find it in the API resource of laravel (Resource, Collection), Ex: PostReource and PostCollection.

Larave Api Resource has two classes you can simply make them using artisan like that.

php artisan make:resource PostResource

This command create a class in App\Http\Resources extends JsonResource

php artisan make:resource PostCollection --collection

or

php artisan make:resource PostCollection

name of the class with suffix collection

this command create a class in App\Http\Resources extends ResourceCollection

so, what is the difference between them?

Resource Class Collection Class
extends JsonResource extends ResourceCollection
mapping for a single model instance $post  mapping for collection of model $posts
new PostResource(Post::find(1));              new PostCollection(Post::paginate())
cannot paginate data, can use paginate and return metadata..
doesn't support additional metadata with the collection.

Tutorial :

Suppose you have a new laravel project and make Post model and posts_table migration has fields title,description,user_id ..

Create PostResource and PostCollection :

 php artisan make:resource Posts/PostCollection
 php artisan make:resource Posts/PostResource
  • edit PostResource toArray to be like that :
public function toArray($request)
    {
        return [
            "title"       => $this->title,
            "description" => $this->description,
            "user"        => new UserResource($this->user)
        ];
    }
  • create userResource class
    php artisan make:resource Users/UserResource
    
  • edit UserResource toArray to be like that :
    public function toArray($request)
      {
          return [
              "name"  => $this->name,
              "email" => $this->email
          ];
      }
    
  • return to posts and edit PostResource toArray :
    public function toArray($request)
      {
          return [
              "status" => true,
              "msg"    => "All Posts",
              "data"   => $this->collection
          ];
      }
    

    Now we are ready to return response posts collection :

  • Add this method in routes/web.php to quick test
    Route::get("test", function () {
      return new PostCollection(Post::paginate());
    });
    
  • Now run the server into the project folder and open this link :
    php artisan ser
    
    localhost:8000/test

Finally: You will receive this response :



Comments

Popular posts from this blog

Laravel Project does not need apache

من الحاجات الغريبة الي اكتشفتها بالصدفة كدا و وقفت قدامها فترة مش فاهم حاجه ... استغربت ان زميلي يعمل run لمشروع Laravel بدون ما يعمل run لل apache server .. php artisan serve بفضل الله لما ركزت كدا شوية روحت اقرأ ملف server.php الي موجود في root folder of laravel project و لقيت السطرين دول الي في screen -------------------- لارافيل معتمد علي built-in PHP web server و بالتالي مش محتاج apache server علشان تعمل run لل project -------------------- من الأسئلة المهمة هنا : هل ممكن نستبدل apache او nginx ب php server ؟ الاجابة باختصار لا و السبب ان السيرفر دا في الاساس اتعمل من أجل developers وليس full feature .. شوف التحذير الي في أول manual هنا PHP Manual References : Github Laravel server.php https://stackoverflow.com/questions/27485505/symfony-apache-vs-built-in-php-server https://www.php.net/manual/en/features.commandline.webserver.php

Software Architecture Styles

تعالوا نتكلم "صنعة باك-إند" بعيداً عن خناقات الفريموركس والمقارنات السطحية. لو سألت أي مطور باك-إند لسه بيبدأ: "إنت بتنظم كودك إزاي؟"، غالباً الإجابة هتكون: "بعمل فولدر للـ Controllers وفولدر للـ Models .. إلخ". لكن لما الـ Scale بيكبر، والـ Requests بتدخل في ملايين، والبزنس شروطه بتتغير كل أسبوع، تنظيم الفولدرات ده مش هيحيلك مشكلة. هنا بقى بنبدأ نتكلم Software Architecture Styles . الـ Architecture مش رفاهية، دي الطريقة اللي السيستم بتاعك بيتنفس بيها. تعالوا نفصص الـ 10 أنواع الأشهر في عالم الـ Back-end والـ System Design عشان ننقل تفكيرنا من مجرد "كاتب كود" لـ "مهندس أنظمة": 1. Monolithic Architecture (الكل في واحد) ده البداية الطبيعية لأي مشروع في الدنيا. الكود كله عبارة عن كتلة واحدة ( Single Unit )، الـ UI والـ Business Logic والـ Database Access كله عايش في نفس الـ Repository ويدخل له Deploy مع بعضه. اللقطة بتاعته: سريع جداً في التطوير والـ Testing في الأول، والـ Deploy بت...

Adapter Design Pattern 😃

  Adapter Design Pattern 😃