I have a middleware that reads the language setting from the database and applies the sets the application locale accordingly:
public function handle($request, Closure $next)
{
$lang = SystemSetting::find('System Language');
\App::setLocale($lang->value);
return $next($request);
}
I would also like to set the text direction (rtl or ltr) so it will be available to my blade template in order to load the necessary css files.
I can easily do it in the controller but i do not wish to repeat it in every controller and pass it to the view for every page in my application. Is there a way to set a global variable or something similar so I can do this in my blade template:
#if ($RTL)
{{ Html::style('css/rtl/app-rtl.css') }}
#else
{{ Html::style('css/app.css') }}
#endif
You can use the view facade, that you can read more about here.
This allows you to directly prepare any data for the views and make it available there.
<?php
use Illuminate\Support\Facades\View;
public function handle($request, Closure $next)
{
$lang = SystemSetting::find('System Language');
\App::setLocale($lang->value);
View::share('rtl', true);
return $next($request);
}
But I would suggest looking into flashing this into the session.
You can change with translation
<html lang="{{config('app.locale')}}" dir="{{#trans('interface.dir')}}">
interface in ar file :
return [
//add this line in ar file
'dir' =>'rtl',
]
interface in en file :
return [
//add this line in en file
'dir' =>'ltr',
]
Related
EDIT: found the answer to all my questions: https://github.com/codezero-be/laravel-localized-routes (and, of course, 42).
I'm working on a multi-language website where the URL's contain localized strings. For instance:
https://site/en/members/john-doe
https://site/nl/leden/john-doe
(and so for every language)
In web.php, I prefixed my routes. Via middleware, I set the current language (retrieved from the first URL-segment). This works fine for everything (both in controllers and in blade)... except for the URLs generated by route(). They are always in the default language. Even though everything else is correctly localized. If I dump app()->getLocale() in a controller of blade it shows the correct language. Only the URLs generated by the route()-function are always in the default fallback language.
I've tried moving my middleware-class higher up in the middleware-groups list. That didn't make a difference.
web.php
Route::prefix('{lang}')->group(function() {
Route::get(trans('routes.members') . '/{username}/', 'MembersController#profile')
->name('members.show');
}
SetLanguage middleware
...
public function handle(Request $request, Closure $next)
{
$lang = $request->segment(1) ?? app()->getLocale();
//set app language
app()->setLocale($lang);
//set default url parameter
URL::defaults(['lang' => $lang]);
return $next($request);
}
...
App\Http\Kernel.php
...
protected $middlewareGroups = [
'web' => [
\App\Http\Middleware\EncryptCookies::class,
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
\Illuminate\Session\Middleware\StartSession::class,
\Laravel\Jetstream\Http\Middleware\AuthenticateSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
\App\Http\Middleware\VerifyCsrfToken::class,
\App\Http\Middleware\SetLanguage::class,
\Illuminate\Routing\Middleware\SubstituteBindings::class,
\App\Http\Middleware\UserLastSeenAt::class,
],
...
Got it (with a little help from a friend)
In the AppServiceProvider's boot function I've added
public function boot(Request $request)
{
//set app language
app()->setLocale($request->segment(1) ?? app()->getLocale());
}
& the SetLanguage-middleware now only contains
public function handle(Request $request, Closure $next)
{
//set default url parameter
URL::defaults(['lang' => app()->getLocale()]);
return $next($request);
}
That did the trick!
Great! I've done the same as you, but i have a problem when i chose to change the lang from switcher.
The switcher in blade:
<a class="ml-1 underline ml-2 mr-2" href="{{ route('change-lang')}}">
<span>{{ $locale_name }}</span>
</a>
The target route:
Route::get('/lang', [LangController::class, 'changeLang'])->name('change-lang');
The function in LangController:
public function changeLang($locale){
App::setLocale($locale);
session()->put('locale', $locale);
return redirect()->back();
}
Let me Exaplain:
If i navigate, for example, in about section and my url is "webname/it/azienda" and i switch language in EN my url becomes "webname/it/en";
I don't have issues if i change language if I have "webname/azienda" or "/" for home page.
I cannot change only the parameters LOCALE without adding it.
Laravel 5.5
Using a group in RouteServiceProvider for {domain}
I want to be able to call Named Routes in blade without having to pass
public function pageName($domain){
return view('mypage', ['domain'=>$domain,'othervars'=>$domain)])
}
and avoid this mess in blade:
{{ route('nameOfRoute', ['domain'=>$domain]) }}
Instead i would love to simply in my route group set the route(['domain']) property to be $domain and be done with it.
No global way to set it, but instead, wrap the route('name') default helper function with my own helper function, and add the param to the array.
Example function:
function orgRoute($route, $params = [])
{
if (!is_array($params)){
$params = [$params];
}
// Set the domain value if not set, null, or jibberish
if (!isset($params['domain']) || $params['domain']=='{domain}' || $params['domain'] == '')
{
// Instance of App Domain is set in OrgBaseController __construct()
$domain = \App::make('current_domain');
$params['domain'] = $domain;
}
return route($route, $params);
}
I am making a bilingual app. I am using same routes for each but I am using different views for both languages. Whenever I want to redirect to a route I want to pass {{ route('test.route', 'en') }}. Where I am passing en, I want to fetch the current locale value from the view and then pass it to the route. Please help.
try this. It will give the locale set in your application
Config::get('app.locale')
Edit:
To use this in blade, use like the following, to echo your current locale in blade.
{{ Config::get('app.locale') }}
If you want to do a if condition in blade around it, it will become,
#if ( Config::get('app.locale') == 'en')
{{ 'Current Language is English' }}
#elseif ( Config::get('app.locale') == 'ru' )
{{ 'Current Language is Russian' }}
#endif
To get current locale,
app()->getLocale()
At first create a locale route and controller :
Route::get('/locale/{lang}', 'LocaleController#setLocale')->name('locale');
class LocaleController extends Controller
{
public function setLocale($locale)
{
if (array_key_exists($locale, Config::get('languages')))
{
Session::put('app_locale', $locale);
}
return redirect()->back();
}
}
Now you can check easily in every page:
$locale = app()->getLocale();
$version = $locale == 'en' ? $locale . 'English' : 'Bangla';
I am trying to pass data to Controller of Laravel. here is how I do that :
in PagesController::
class PagesController extends Controller
{
public function contact(){
$data="some random ";
return view('contact',compact("data"));
}
}
now in contact.blade.php :
contact pages {{ $data }}
and it s hows
Whoops, looks like something went wrong.
What may be a problam?
try this
public function contact()
{
$data = 'some random';
return View('contact')->with('data' , $data );
}
make sure that the view works fine (if its inside a folder use return View('foldername.contact')
make sure that your view name is contact.blade.php (check uppercase letters)
and inside your view
this is my {{ $data }}
I am new to laravel and following a tutorial for a basic app. So far the app has a default view layouts/default.blade.php, a partial _partials/errors.blade.php and three other views questions/index.blade.php, users/new.blade.php and users/login.blade.php
The routes are defined like so
// home get route
Route::get('/', array('as'=>'home', 'uses'=>'QuestionsController#get_index'));
//user register get route
Route::get('register', array('as'=>'register', 'uses'=>'usersController#get_new'));
// user login get route
Route::get('login', array('as'=>'login', 'uses'=>'usersController#get_login'));
//user register post route
Route::post('register', array('before'=>'csrf', 'uses'=>'usersController#post_create'));
// user login post route
Route::post('login', array('before'=>'csrf', 'uses'=>'usersController#post_login'));
questions/index.blade.php and users/new.blade.php load fine and within default.blade.php
when I call /login a blank page is loaded not even with default.blade.php. I am guessing that there is a problem in my blade syntax in login.blade.php given the fact that the default.blade.php works on the other routes and as far as I can see everything else is the same but if that was teh case wouldnt the default.blade.php route at least load?
the controller method this route is calling is as follows
<?php
Class UsersController extends BaseController {
public $restful = 'true';
protected $layout = 'layouts.default';
public function get_login()
{
return View::make('users.login')
->with('title', 'Make It Snappy Q&A - Login');
}
public function post_login()
{
$user = array(
'username'=>Input::get('username'),
'password'=>Input::get('password')
);
if (Auth::attempt($user)) {
return Redirect::Route('home')->with('message', 'You are logged in!');
} else {
return Redirect::Route('login')
->with('message', 'Your username/password combination was incorrect')
->withInput();
}
}
}
?>
finally login.blade.php
#section('content')
<h1>Login</h1>
#include('_partials.errors')
{{ Form::open(array('route' => 'register', 'method' => 'POST')) }}
{{ Form::token() }}
<p>
{{ Form::label('username', 'Username') }}
{{ Form::text('username', Input::old('username')) }}
</p>
<p>
{{ Form::label('password', 'Password') }}
{{ Form::text('password') }}
</p>
<p>
{{ Form::submit('Login') }}
</p>
{{ Form::close()}}
#stop
You could also define the layout template directly from the Controller , this approach provides more flexibility , as the same View can be used with multiple layout templates .
<?php namespace App\Controllers ;
use View , BaseController ;
class RegisterController extends BaseController {
protected $layout = 'layouts.master';
public function getIndex()
{
// Do your stuff here
// --------- -------
// Now call the view
$this->layout->content = View::make('registration-form');
}
}
My example uses Namespaced Controller but the same concepts are applicable on non-Namespaced Controllers .
Notice : Our RegisterController extends Laravel's default BaseController , which makes a bit of preparation for us , see code below :
<?php
class BaseController extends Controller {
/**
* Setup the layout used by the controller.
*
* #return void
*/
protected function setupLayout()
{
if ( ! is_null($this->layout))
{
$this->layout = View::make($this->layout);
}
}
}
If a custom "Basecontroller" is defined , make sure that it also implements the "preparation" code .
I don't know what concepts are new to you , so let me make a couple arbitrary assumptions . If "namespace" and "Basecontroller" are << strange words >> , let me try to demystify these words .
Namespace : PHP's documentation is pretty well documented on this subject . My oversimplified explanation is as follows : Two skilled developers (JohnD and Irish1) decide to build their own PHP Logging Library and release the code as open source to the community .Most likely they will name their library "Log"
Now another developer would like to implement both libraries into his/her project (because JohnD's code uses MongoDB as storage medium while Irish1's code uses Redis ) . How would PHP's interpreter distinguishes the two code-bases from each other ? Simply prepend each library with a vendor name (JhonD/Log and Irish1/Log ) .
Basecontroller : Most likely your Controllers will share common functionality (a database connection , common before/after filters , a common template for a View ...... ) . It is a good practice not to define this "common functionality" into each Controller separately, but define a "Parent" Controller , from which all other Controllers will inherit its functionality . So later on , if you decide to make changes on the code , only one place should be edited .
My previous example uses " class RegisterController extends BaseController " , that BaseController is just checking if our (or any other) Child-controller has defined a property with the name of " $layout " , and if so , the View that it will instantiate will be encapsulated into that specified layout . See Laravel's flexibility , a group of Controllers share common functionality (by extending Basecontroller) but also are free to choose their own layout (if they desire to do so ) .
I have found my error
I did not have #extends('layouts.default') at the beginning of the login.blade.php template