laravel-translatable
laravel-translatable copied to clipboard
getting special languages posts with laravel-translatable
I am using this library for developing a multi-language web system. In this web application, there is no front-end, and the data is read and written through APIs. The problem I am facing is that I cannot fetch all the records stored in the database in one or more languages, for example, all records from the 'blog' table where the title is in English and French. The library documentation does not explicitly mention this, and I could not solve the issue with the codes I have tested. The following are the code examples I tried, but none of them resolved my problem:
// 1)
Route::get('/', function () {
return response()->json(
DB::table('blogs')
->get()
->filter(function ($blog) {
return $blog->getTranslations('title', ['en']);
})
);
});
// 2)
Route::get('/', function () {
return response()->json(
DB::table('blogs')
->get()
->filter(function ($blog) {
return collect(json_decode($blog->title))->has('en');
})
);
});
// 3)
Route::get('/', function () {
return response()->json(Blog::titleEqualsEn()->get(), 200);
});
using middleware solution:
class Language
{
public function handle(Request $request, Closure $next)
{
$locales = ['fa', 'en', 'de'];
if ($request->has('lang') && in_array($request->input('lang'), $locales)) {
App::setLocale($request->input('lang'));
}
return $next($request);
}
}
'api' => ['throttle:api', SubstituteBindings::class, Language::class],
model:
class Blog extends Model implements HasMedia
{
use HasTranslations, InteractsWithMedia;
public array $translatable = ['title', 'content'];
and then:
GET http://localhost:8000/api/blogs/blogs?lang=en
as French language is selected by the user from the frontend section, the data does not come in the form of French as I understand the problem. For this, you need to pull the data from there by keeping the language coming from the user in a place such as a session.
example: https://github.com/tugranDemirel/tour-agency/blob/master/app/Http/Middleware/Localize.php
https://github.com/tugranDemirel/tour-agency/blob/master/app/Http/Controllers/FrontController.php (line 113)
You are supposed to use it with Eloquent, but your examples show the usage of a plain QueryBuilder.
Dear contributor,
because this issue seems to be inactive for quite some time now, I've automatically closed it. If you feel this issue deserves some attention from my human colleagues feel free to reopen it.