Fairly new to Laravel and I'm trying to add a functionality that allows the user to switch between two languages by clicking a button in a header.blade.php file. So far I've got it so there's a test.php file in the respective lang directories with test strings and have managed to get <p>{{__('test.test')}}</p> to display the correct language when manually set. At the moment I'm not sure if this is actually calling the route to update the language or if the logic I have for updating it is wrong since I get no errors and I'm using barryvdh/laravel-debugbar to debug.
My logic for the button:
<button href="{{ url('language', config('app.locale') == 'en' ? 'fr' : 'en') }}">{{ config('app.locale') }}</button>
In routes/web.php:
Route::get('/language', 'LanguageController#show');
Route::post('/language/{lang}', 'LanguageController#update');
LanguageController.php, created via php artisan make:controller --api
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class LanguageController extends Controller
{
/**
* Display the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function show($id)
{
return App::getLocale();
}
/**
* Update the specified resource in storage.
*
* #param \Illuminate\Http\Request $request
* #param int $id
* #return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
//Tried the following
config(['app.locale' => $id]);
App::setlocale($id);
}
}
Questions:
Is this the correct way to update the language at runtime?
How can I tell if my api calls are being made?
How can I achieve this inside of a template .vue file?
Is making a Controller for the language redundant?
Would the inner HTML of my button change if the locale was changed?
Is affecting config files at runtime bad practice?
--Edit--
I should also mention that the only reason I made a controller for this is because I had the route calls in web.php use a function instead however, they stated they were Closure running php artisan route:list and with the research I found I couldn't tell if that was correct
You are on the right way, but there is something missing.
You can't use the configuration to edit at runtime the language.
Save local language in user Session and create a new middleware to set on each request the language saved in session.
I found this article that can help you, localization-laravel
Related
I am looking for a way to show a specific view only to specific visitors who get a link to that view. How can I make a middleware so that shows the view only if it comes from a specific source (like if it comes from source.blade.php)
I cannot use the middleware for guest or auth, because then it would give that view to all the auth, but I only want give that view to an auth who has made a payment at beginning and have been redirected from a specific URL.
How can I setup a middleware in such a way that it only shows the view if the auth is being redirected from another view like - source.blade.php
Currently, I have this page setted up like this
public function __construct()
{
$this->middleware('auth:client');
}
This works well, it only shows this page to someone who has logged in from the client authentication guard, but the problem is, any client can visit this page.
I am looking for a way to make it so that it can viewed only by the client who paid at the beginning, and were re-directed by my website. Maybe something like
public function __construct()
{
if(redirect_source="source.blade.php") {$this->middleware('auth:client'); }
}
I think you want a solution that will limit the permission based on your user type.
Middlewares are used to condition certain parameters if you want to let the requester to go into the specific url/route and not to control inside your views.
So if you want to control it, you can use this solution .
namespace App\Laravel\Middleware\Backoffice;
use Closure;
use Illuminate\Contracts\Auth\Guard;
use Illuminate\Http\RedirectResponse;
use Auth, Session;
class ValidSuperUser {
/**
* The Guard implementation.
*
* #var Guard
*/
protected $auth;
/**
* Create a new filter instance.
*
* #param Guard $auth
* #return void
*/
public function __construct(Guard $auth)
{
$this->auth = $auth;
}
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle($request, Closure $next)
{
if($this->auth->user()->type != "super_user") {
Session::flash('notification-status','failed');
Session::flash('notification-title',"Access Denied");
Session::flash('notification-msg','You are not allowed to view the page you are tring to access.');
return redirect()->route('backoffice.dashboard');
}
return $next($request);
}
}
in your Kernel.php under Http folder declare the new Middleware in order to use.
**put it under protected $routeMiddleware = []
and then use it to your routes that need to help that kind of user type.
$route->group(['middleware' => "aliasofyournewmiddle"],function(){
//some routes here
});
your new middleware can be any condition upon the request, so any inputs and available session that has been passed to that url are usable on that middleware, adjust it on how you want to handle the situation.
You can pass a token when redirecting your users to your specific page. Then use your middleware to check whether that token is valid or not.
Say for example, someone made a payment at beginning, you store a hash value of that person's user id or any unique identifier in a session, then redirect the user with the same hash value included in your url. Your middleware can then handle the validation, if the value stored in the session is the same with the value provided in the url.
I have a Laravel 5.2 app and inside the public_html folder I have some assets stored in a subfolder called metronic as I am using a theme called metronic and wanted to keep it all bundled in one place to make updating it easier.
I have linked to these assets using the URL::asset() method like so:
<script src="{!! URL::asset('metronic/global/plugins/fullCalendar/fullcalendar/fullcalendar.js') !!}"></script>
This generates the following URL:
http://www.mywebsite.com/metronic/global/plugins/fullCalendar/fullcalendar/fullcalendar.js
For some reason this is working fine locally but when I run it on my production server the request is going through Laravel. I have some middleware that checks whether or not to show the coming soon page and this is being run and so rather than the script being fetched the holding page is just being run. This is the content of the middleware:
<?php namespace App\Http\Middleware;
use Closure;
use Request;
use Route;
use Session;
class HoldingPageCheck {
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle($request, Closure $next)
{
if(env('HOLDING_PAGE')==true && (!$request->is('coming-soon') && !$request->is('member/subscribe') && !$request->is('migrate') && !$request->is('contact') && $request->segment(1)!='admin')) {
Session::reflash();
return redirect(route('holding_page'));
}
return $next($request);
}
}
It doesn't make any sense to me why Laravel would be interfering with an asset request it should just bypass Laravel entirely shouldn't it when a request for a JS file is made?
Found the problem, it was because I was using camel case in the path to the script. Locally with xampp it didn't mind but obviously my live environment was case sensitive.
I'm using 2 languages in my Laravel 5.2 app. There is a simple password-reminder page I'm implementing currently, and for reasons unknown to me I have problems in sending the new-password email in the correct language.
Let's say I see the page in German. In the view of the page, I echo 2 values, using Facades:
echo App::getLocale();
echo Session::get('locale');
The page is served in German, so both values echo de.
Now, I enter an email address into the form and submit it. The input gets to a controller method and calls a library to send a new password to the user:
public function resetPassword() {
// Validate the input, retrieve the user...
Mailer::sendNewPasswordEmail($user); // Call to the library sending emails
}
Finally, in the library, I var_dump the same 2 values, like this:
public static function sendNewPasswordEmail($user) {
var_dump(App::getLocale());
var_dump(Session::get('locale'));
die;
}
In this case, Session::get('locale') still equals de, but App::getLocale() shows en.
Why, why, why?
In my email template, I'm using the Blade's #lang() directive. As far as I know, the directive checks the application locale to determine which translation to serve. In my case, the email is being sent always in English and I have no clue why App::getLocale() returns a different value in the view and during the next POST request I'm making.
This is not the first time this happens, btw. At times is seems that views "know" more about the actual application locale, than the controllers, models or libraries. Confusing.
Ideas?
Laravel 5.2 App_Locale is not persistent. the only way I've found to make locales work properlly is creating a middleware that calls App::setLocale() like this:
<?php namespace App\Http\Middleware;
use Closure;
use Session;
use App;
use Config;
class Locale {
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle($request, Closure $next)
{
App::setLocale(Session::get('locale'));
return $next($request);
}
}
Register your middleware on Kernel.php
protected $middleware = [
.
.
.
'App\Http\Middleware\Locale'
];
I have got a problem with my Laravel application - I am not able to change my app language and keep it set. After the next request to the server it goes back to default language set. The only thing which is possible is to change the default language in app.php file. I have recently updated my app to Laravel 5.22 - could it be connected with the problem mentioned above?
Would you have some kind of advice on this?
Thank you in advance for any kind of help
in you route group each time load the language
Route::group(['namespace' => 'Language'], function () {
require (__DIR__ . '/Routes/Language/Language.php');
});
in language.php(i have loaded in different route directory )
Route::get('lang/{lang}', 'LanguageController#swap');
in LaunguageController store in session to persist the selection
class LanguageController extends Controller
{
/**
* #param $lang
* #return \Illuminate\Http\RedirectResponse
*/
public function swap($lang)
{
session()->put('locale', $lang);
return redirect()->back();
}
}
I've this route defined in a controller:
/**
* #Secure(roles="IS_AUTHENTICATED_FULLY")
* #Route(
* "/proccess/{slug}",
* requirements={"slug": "^([a-zA-Z0-9]*-[a-zA-Z0-9]*)+$"},
* name="registerRPNI"
* )
*/
public function indexAction(Request $request)
{
......
}
And I need to set the right route in KNPMenuBundle MenuBuilder class. I'm doing as follow:
->addChild('Process RPNI', array(
'uri' => '/process/national-and-imported-products-registration',
))
And it works for dev environment since route shows the right page and execute the right code but if I move away from dev and goes live to prod then I got a 404 Not found, what I'm doing wrong in this case? What should be the right way to generate the routes inside the MenuBuilder class? Any advice around this?