underwear / laravel-translatable-json-resource
Spatie Laravel translatable + Laravel JsonResource
v1.0.0
2021-10-21 20:17 UTC
Requires
- laravel/framework: ~8.0
- spatie/laravel-translatable: ~4.0
README
Spatie laravel translatable package + Laravel JsonResource
Installation
composer require underwear/laravel-translatable-json-resource
Usage
Require this package in your project and use TranslatableJsonResource
instead of JsonResource
.
You don't need to worry about things, just keep using JsonResource as you're used to.
Have a look:
<?php namespace App\Http\Resources; use Illuminate\Http\Resources\Json\JsonResource; use Underwear\LaravelTranslatableJsonResource\TranslatableJsonResource; class ArticleResource extends TranslatableJsonResource { public function toArray($request) { return [ 'id' => $this->id, 'title' => $this->title, // translatable field, 'body' => $this->body, // translatable field 'created_at' => $this->created_at ]; } }
You only need to pass one additional argument locale
:
use App\Http\Resources\ArticleResource; use App\Models\Articles; Route::get('/article/{id}', function ($id) { $article = Article::findOrFail($id); $locale = 'en'; return new ArticleResource($article, $locale); });
It also works with anonymous collections:
use App\Http\Resources\ArticleResource; use App\Models\Articles; Route::get('/articles', function () { $articles = Article::all(); $locale = 'ru'; return ArticleResource::collection($articles, $locale); });
If you don't pass locale argument, it will use default locale from config('app.locale')