Home  >  Q&A  >  body text

Use laravel-translatable to get Laravel articles in a specific language.

<p>I am using the laravel-translatable library to develop a multi-language website system. In this web application, there is no front-end and data is read and written through the API. The problem I am facing is that I am not able to get all the records stored in the database in one or more languages, for example from the 'blog' table I am getting all the records with titles English and French. The documentation for this library doesn't explicitly mention this, and I haven't been able to fix it with the code I've tried. Here are code examples I tried, but none solved my problem: </p> <pre class="brush:php;toolbar:false;">Route::get('/', function () { return response()->json( DB::table('blogs') ->get() ->filter(function ($blog) { return $blog->getTranslations('title', ['en']); }) ); }); Route::get('/', function () { return response()->json( DB::table('blogs') ->get() ->filter(function ($blog) { return collect(json_decode($blog->title))->has('en'); }) ); }); Route::get('/', function () { return response()->json(Blog::titleEqualsEn()->get(), 200); });<span style="font-family:'sans serif, tahoma, verdana, helvetica';"><span style="white-space:nowrap;"> </span></ span></pre> <p><br /></p>
P粉598140294P粉598140294416 days ago531

reply all(1)I'll reply

  • P粉541565322

    P粉5415653222023-08-01 10:27:03

    You can handle the locale for each request by creating a middleware, like this example:

    public function handle(Request $request, Closure $next)
        {
            $locales = ['en', 'fr'];
    
            if($request->has('lang') && in_array($request->input('lang'), $locales)){
                App::setLocale($request->input('lang'));
            }
            return $next($request);
        }

    After that you can easily pass your desired locale as a query string to your endpoint.

    GET http://localhost:8000/api/users?lang=en

    Also, make sure to use the Eloquent model instead of the query builder.

    reply
    0
  • Cancelreply