jamosaur / foundation
Foundation for API's in Laravel
Installs: 2 676
Dependents: 0
Suggesters: 0
Security: 0
Stars: 0
Watchers: 1
Forks: 0
Open Issues: 0
pkg:composer/jamosaur/foundation
Requires
- php: ^8.2
- illuminate/http: ^10.0|^11.0|^12.0
- illuminate/routing: ^10.0|^11.0|^12.0
- illuminate/support: ^10.0|^11.0|^12.0
- spatie/laravel-fractal: ^6.0
Requires (Dev)
- laravel/pint: ^1.27
- mockery/mockery: ^1.4
- orchestra/testbench: ^6.0|^7.0|^8.0|^9.0|^10
- phpunit/phpunit: ^9.0|^10.0|^11.0
README
What is this?
This is the base that I like to use for constructing API's with Laravel.
It is essentially a wrapper for Spatie's laravel-fractal.
Installation
composer require jamosaur/foundation- Update your API controllers to extend
Jamosaur\Foundation\ApiController. This extends the default Laravel controller but also adds more methods that we will use. - Update your API middleware in
app\Http\Kernel.phpto useJamosaur\Foundation\Middleware\ApiRequestMiddleware
Example Usage
Controller
<?php declare(strict_types=1); namespace App\Http\Controllers; use App\Models\User; use Illuminate\Http\JsonResponse; use Jamosaur\Foundation\ApiController; class UserController extends ApiController { public function index(): JsonResponse { $users = User::all(); // By default, this will attempt to transform the data with // `\App\Transformers\UserTransformer`. The package takes replaces // the `Controller` in the controller name with Transformer // and attempts to load it from the `\App\Transformers\ namespace. return $this->transformCollection('users', $users) ->respond(); } public function differentNamespace(): JsonResponse { $users = User::all(); // You can define a different namespace for transformers. return $this->setTransformerNamespace('\\App\\Domain\\Transformers') ->transformCollection('users', $users) ->respond(); } public function chainingTransformers(): JsonResponse { $user = User::all(); $posts = Post::all(); $photo = Photo::query()->first(); // You can also chain methods to transform multiple // sets of data. return $this->setTransformer(new UserTransformer()) ->transformCollection('users', $users) ->setTransformer(new PostTransformer()) ->transformCollection('posts', $posts) ->setTransformer(new PhotoTransformer()) ->transformItem('photo', $photo) ->respond(); } public function definedTransformer(): JsonResponse { $users = User::query()->with('profile')->get(); // You can override which transformer is used, and also pass in // any includes. return $this->setTransformer(new CustomTransformer(), ['profile']) ->transformCollection('users', $users) ->respond(); } }
Important Notes
- Transformers MUST implement
Jamosaur\Foundation\Contracts\TransformerContractand extendLeague\Fractal\TransformerAbstract