Use laravel-translatable to get Laravel articles in a specific language.
P粉598140294
P粉598140294 2023-07-31 15:35:41
0
1
569
<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粉598140294
P粉598140294

reply all(1)
P粉541565322

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.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!