API resources In Laravel
Sumit Mishra
Php Architect || Technical Strategist || IT Consultant || Help You In Building IT Team || Project Outsourcing
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:
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
Laravel API resources provide a clean and maintainable way to structure your API responses, making it easier to manage and version your API.