Loading lang files in Laravel depending on prefix/session - laravel

I build a multilanguage site with 3 languages (mk - default, sq and en) and ended up with the following code in routes.php:
$languages = array('en', 'sq');
$locale = Request::segment(1);
if(in_array($locale, $languages)){
\App::setLocale($locale);
}else{
$locale = null;
}
// Set the session here
Session::put('locale', $locale);
Route::group(array('prefix' => $locale), function()
{
Route::get('/', array('as' => 'home', 'uses' => 'Controllers\Frontend\FrontendController#getIndex'));
// .... other routes
});
My default locale is 'mk' and I also have 2 other languages in Land folder, sq and en.
While the routing works fine, problem is when loading lang files. It works for default language mk set in app.php and for en but won't switch for sq translation, and instead it loads the en lang files.
Example:
URL: http://website.com loads mk lang files
URL: http://website.com/en loads en lang files
URL: http://website./sq loads en lang files instead of sq <--- PROBLEM
Among other code, I have the following in the view:
{{{ URL::route('home') }}}
The controller is usual:
public function getIndex($locale = null)
{
$data = array();
return View::make('frontend.frontpage', $data);
}
My question: why the sq language files aren't loaded when the URI parameter is changed to sq?

Question: "Loading lang files in Laravel depending on prefix/session"
#Pat's answer (in comment) solved my issue (Loading lang files in Laravel depending on prefix/session)
In short, using https://github.com/mcamara/laravel-localization eases creating multilangugage website with Lavarel.

Related

Laravel / vue-froala-wysiwyg integration

I'll like to implemente the image upload system within my Laravel/VueJS project but I can't find a right way to do so. How can I set up my Controller function in order to handle this upload?
Edit:
This is my Editor configuration:
config: {
imageUploadParam: 'imageFile',
imageUploadURL: '/froala/upload/image',
imageUploadMethod: 'POST',
imageMaxSize: 5 * 1024 * 1024,
imageAllowedTypes: ['jpeg', 'jpg', 'png'],
}
And this is the function that handles the request:
public function uploadImage(Request $request)
{
$file = $request['imageFile'];
$name = $file->getClientOriginalName();
$name = strtolower(str_replace(' ', '', $name));
$path = $file->hashName();
$image = Image::make($file);
Storage::put("/threads/{$path}", (string) $image->encode());
$multimedia = Multimedia::create([
'name' => $name,
'path' => $path
]);
return ['link' => $multimedia->path];
}
I am using the Intervention Image library to handle the image upload.
Edit 2:
I'm getting an 419 error related with the csrf token. So, how can i pass it to the function? I know how to get it but using the imageUploadParams configuration of the editor is not working:
imageUploadParams: {
csrf: this.csrf
}
csrf: document.querySelector('meta[name="csrf-token"]').getAttribute('content'),
You need to pass the correct X-CSRF-TOKEN value to avoid the 419 error.
First check that you have the token defined the in the meta header with something like:
<meta name="csrf-token" content="{{ csrf_token() }}">
Early in your VueJS add:
var csrf_token = $('meta[name="csrf-token"]').attr('content');
Then add the following to your Froala config section:
config: {
requestHeaders: {
'X-CSRF-TOKEN': csrf_token
},
Media files should now pass through to your media upload function in Laravel.
From the documentation :
When an image is inserted into the WYSIWYG HTML editor, a HTTP request is automatically done to the server.
The specific URL that the request will be made to can be specified using the imageUploadURL config option.
Setup your routes.php file to properly direct the request to your controller of choice :
Route::post('/upload', 'FilesController#store');
Then, in your controller you can handle the image upload like you would normally. The important part is that you return the path to the file after you've saved it.
The returned JSON needs to look like: { "link": "path/to/image.jpg" }
Here is an example of what that could look like :
public function store(){
$filepath = request()->file('file')->store('images', 'public');
return ['link' => $filepath];
}
Of course, feel free to do any kind of validation or processing that you need.
instand of
imageUploadParams: {
csrf: this.csrf
}
use this
imageUploadParams: {
_token: this.csrf
}
Check this out From Documentation

Switching language in laravel 5 / vue app2

In my laravel 5.6/vue.js 2.5.7 / I use
vue-i18n 7.8 and laravel-vue-i18n-generator for multi language support:
and in resources/assets/js/app.js file I do like:
...
let lang = 'fr';
const i18n = new VueI18n({ // https://github.com/caouecs/Laravel-lang - Additive langs
locale: lang, // set locale
messages : Locale, // set locale messages
})
new Vue({ router, i18n,
data:{
...
In my vue file wnen I need to read my current locale I can use like :
created() {
this.current_locale = this.$i18n;
...
To switch to other locale locale I can use a function like:
switchLocale () {
if (this.$i18n.locale === 'fr') {
this.$i18n.locale = 'en'
} else {
this.$i18n.locale = 'fr'
}
}
The question is where to save current language when I moving to other page? I mean
let lang = 'fr';
at top of my code that is some default locale, but if locale has been changed, where from to read it? Some simple solution please.
To generate prefix in url seems very complicated.
Thanks!
You could use localStorage.
switchLocale () {
if (this.$i18n.locale === 'fr') {
this.$i18n.locale = 'en'
} else {
this.$i18n.locale = 'fr'
}
localStorage.setItem('locale', this.$i18n.locale)
}
And then on the next page:
this.$i18n.locale = localStorage.getItem('locale');

Site direction base on language in laravel

I'm working with laravel 5.4 and my application supports both LTR and RTL languages, my question is how can I redirect my content when user choose RTL language and reverse of it obviously?
I had same question and after some investigations i did following process:
added following code to my language file:
'page_direction' => 'rtl',
you can learn more about this subject on Laravel Localization documentations.
After this added following code to my master template:
class="{{ __('global.page_direction') }}"
At this time i can define special CSS code when body element have rtl class like this:
body.rtl .element{float:right}
You'll want look in to incorporating Laravel's localization features for this.
https://laravel.com/docs/5.4/localization
Each language has it's translated phrases stored in the resources/lang directory. Then based on the user's browser settings the application will display the correct translated text.
You may try writing an JS function for onchange event of RTL or LTR
$(document).on('change', '#language_selector' , function() {
var locale = $(this).val();
$.ajax({
url: "{{ url('change_language') }}",
type: "POST",
data: {
locale: locale
},
success: function() {
window.location.reload();
}
});
});
and attach a route to set the locale
Route::post('change_language', function() {
$locale = Input::get('locale');
App::setLocale($locale);
});
and in your view based on the locale you could set the style css
#if(App::getLocale() == 'en')
<link href="ltr.css" type="stylesheet" />
#else
<link href="rtl.css" type="stylesheet" />
#endif

How to point digest assets file inside an js file in phoenix

How do I point file url from a js file? Here's a code snippet that I would like to implement.
const currentCacheName = "sample-app-v2";
self.addEventListener('install', (event) => {
const urlToCached = [
'/',
'<%= static_path(#conn, "/css/app.css") %>', // Adding .eex on the js file won't work.
'<%= static_path(#conn, "/js/app.js") %>'
// Add fonts, icon, etc.
];
event.waitUntil(
caches.open(currentCacheName).then(function(cache) {
return cache.addAll(urlToCached);
})
);
});
self.addEventListener('activate', (event) => {
event.waitUntil(
caches.keys().then((cacheNames) => {
return Promise.all(
cacheNames.filter((cacheName) => {
return cacheName.startsWith('sample-app-') && cacheName != currentCacheName;
}).map((cacheName) => {
return cache.delete(cacheName);
})
);
})
);
});
self.addEventListener('fetch', (event) => {
event.respondWith(
caches.match(event.request).then(function(response) {
if(response) return response;
return fetch(event.request);
})
);
});
I'm trying out phoenix with serviceworker but I need to get the latest digest assets file for it to work.
There are several ways of doing such thing. One of it is to convert your JS file from a static asset to a template – create route for this, controller, view and move JS code to a template file (for example – script.js.eex under web/templates/script/ if you named you controller like ScriptController and view is the ScriptView). In that case you will be able to use template tags inside of JS code, and serve your script from the root of web app if you need. This is completely similar to adding new routes/pages to your Phoenix app. Also you should disable forgery protection for such route (remove :protect_from_forgery from a pipeline in router). Cons of this is that you'll lose all JS pipeline for this script, so no transpiling and other stuff like this.

Difficulties with routes translation and api

I am creating an API for my project and I have the following problem:
I'm using the location files.
Route::group(array('prefix' => Config::get('app.locale_prefix')), function()
{
Route::get('{contact}', 'WelcomeController#index');
});
This part of code works correctly, and I can access with
http://localhost/project/public/en
However, I am interested in create an API to receive a list of products. So I add this code:
Route::group(array('prefix' => Config::get('app.locale_prefix')), function()
{
Route::get('{contact}', 'WelcomeController#index');
Route::group(['prefix' => 'api'], function() {
Route::get('test', function(){
return response()->json(['foo'=>'bar']);
});
});
});
I don't have any errors, but I can't receive a response. What is the problem?
http://localhost/project/public/en/api/test
UPDATED
I solve part os this problem , in the view I have this
<li><?= trans('locale.allauctions'); ?></li>
This works correctly but I need to put en/anotherurl , how can I put this ?
http://localhost/project/public/api/test is working fine.
This is because your Config::get('app.locale_prefix') is empty! So you defined there is NO prefix. Use dd(Config::get('app.locale_prefix')); to test it.
Why is http://localhost/project/public/en working then?
Because you defined a variable {contact} in
Route::get('{contact}', 'WelcomeController#index');
and en is {contact} then.

Resources