API resources In Laravel

API resources In Laravel

In Laravel, API resources provide a convenient way to transform and format your Eloquent models and collections into a structured format that can be easily consumed by your API clients. API resources help in standardizing the response format and can be useful in versioning APIs and controlling what data is exposed.

Here's a simple example of using Laravel API resources:

  1. Create a Model:Let's assume you have a Post model:

php artisan make:model Post -m        

In app/Models/Post.php:

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
    protected $fillable = ['title', 'content'];
}        

Run migration:

php artisan migrate        

2. Create a Resource:

Next, create a resource for the Post model:

php artisan make:resource PostResource        

In app/Http/Resources/PostResource.php:

<?php

namespace App\Http\Resources;

use Illuminate\Http\Resources\Json\JsonResource;

class PostResource extends JsonResource
{
    public function toArray($request)
    {
        return [
            'id' => $this->id,
            'title' => $this->title,
            'content' => $this->content,
            'created_at' => $this->created_at,
            'updated_at' => $this->updated_at,
        ];
    }
}        

3. Use the Resource in a Controller: Now, use the PostResource in a controller:

In app/Http/Controllers/PostController.php:

<?php

namespace App\Http\Controllers;

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

class PostController extends Controller
{
    public function show($id)
    {
        $post = Post::findOrFail($id);

        return new PostResource($post);
    }
}        

4. Define API Route:

Define a route in routes/api.php:

use App\Http\Controllers\PostController;

Route::get('/posts/{id}', [PostController::class, 'show']);        

5. Test the API:

Start your Laravel development server:

php artisan serve        

  1. Now, you can access the API endpoint at https://127.0.0.1:8000/api/posts/{id} (replace {id} with the actual ID of a post).This will return a JSON response formatted according to the PostResource. You can customize the resource's toArray method to include or exclude specific fields as needed.

Laravel API resources provide a clean and maintainable way to structure your API responses, making it easier to manage and version your API.

要查看或添加评论,请登录

Sumit Mishra的更多文章

  • CSS Specificity

    CSS Specificity

    CSS specificity is a set of rules used to determine which styles are applied to an element when multiple conflicting…

  • Install & Run Typescript

    Install & Run Typescript

    To compile TypeScript code into JavaScript, you need to have the TypeScript compiler () installed. You can install it…

  • Php 8 New Concepts

    Php 8 New Concepts

    PHP 8 introduced several new features and improvements. Here are some of the key concepts with examples: Named…

  • useRef Hook In React Js

    useRef Hook In React Js

    In React, the hook is used to create a mutable object called a ref. This ref can be attached to a React element and can…

  • Children In React Js

    Children In React Js

    In React.js, handling children is a fundamental aspect of building components.

  • Destructuring In JavaScript

    Destructuring In JavaScript

    Destructuring is a feature in JavaScript that allows you to extract values from arrays or properties from objects and…

  • Abstract Data Type In Detail

    Abstract Data Type In Detail

    An Abstract Data Type (ADT) is a high-level description of a set of operations that can be performed on a particular…

  • Flux Pattern In React Js With Example

    Flux Pattern In React Js With Example

    Install Dependencies: You'll need to install package. You can install it using npm or yarn: or Implement Flux…

  • Rules of Hooks In React Js

    Rules of Hooks In React Js

    In React, hooks are functions that allow you to use state and other React features in functional components. The most…

  • What is Cron Jobs. How to Implement Cron Jobs in Php

    What is Cron Jobs. How to Implement Cron Jobs in Php

    Cron jobs in PHP are scheduled tasks that run automatically at predefined intervals on a Unix-based system. These tasks…

社区洞察

其他会员也浏览了