Laravel 5.4 proper way to store Locale setLocale() - laravel

I need to know. What is the proper way to store Locale for user. If for each users' request I change the language by
App::setLocale($newLocale);
Would not it change language for my whole project and for other requests as well? I mean when one user changes language it will be used as default for other users.
Thanks in advance

If you set App::setLocale() in for example in your AppServiceProvider.php, it would change for all the users.
You could create a middleware for this. Something like:
<?php
namespace App\Http\Middleware;
use Closure;
class SetLocale
{
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle($request, Closure $next)
{
app()->setLocale($request->user()->getLocale());
return $next($request);
}
}
(You need to create a getLocale() method on the User model for this to work.)
And then in your Kernel.php create a middleware group for auth:
'auth' => [
\Illuminate\Auth\Middleware\Authenticate::class,
\App\Http\Middleware\SetLocale::class,
],
And remove the auth from the $routeMiddleware array (in your Kernel.php).
Now on every route that uses the auth middleware, you will set the Locale of your Laravel application for each user.

I solved this problem with a controller, middleware, and with session.
This worked for me well, hope it helps you.
Handle the user request via the controller:
Simply set the language to the users session.
/**
* Locale switcher
*
* #param Request $request
* #return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
*/
public function switchLocale(Request $request)
{
if (!empty($request->userLocale)) {
Session::put('locale', $request->userLocale);
}
return redirect($request->header("referer"));
}
Route to switch locale:
Route::post('translations/switchLocale}', ['as' => 'translations.switch', 'uses' => 'Translation\TranslationController#switchLocale']);
Middleware to handle the required settings:
In the Middleware check the user's session for the language setting, if its pereset set it.
/**
* #param $request
* #param Closure $next
* #param null $guard
* #return mixed
*/
public function handle(Request $request, Closure $next, $guard = null)
{
if (Session::has('locale')) {
App::setLocale(Session::get('locale'));
}
}
Lastly the switching form:
{!! Form::open(["route" => "translations.switch", "id" => "sideBarLocaleSelectorForm"]) !!}
{!! Form::select("userLocale", $languages, Session::get("locale")) !!}
{!! Form::close() !!}
<script>
$(document).on("change", "select", function (e) {
e.preventDefault();
$(this).closest("form").submit();
})
</script>

When someone loads your website it uses the default which is set in the config file.
The default language for your application is stored in the config/app.php configuration file.
Using the App::setLocale() method would only change for a specific user which I assume would be set in the session, the config file value would not be altered.
You may also change the active language at runtime using the setLocale method on the App facade
You could see this in action yourself by opening your website in two different browsers (as they would be using two different sessions) then changing the locale in one and seeing the default load in the other.
https://laravel.com/docs/5.4/localization#introduction

You could create a middleware like below.
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
class SetLocale
{
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle(Request $request, Closure $next)
{
if (auth()->check() && $languageId = auth()->user()->language_id) {
$locale = Language::find($languageId)->locale;
app()->setLocale($locale);
}
if ($request->lang) {
app()->setLocale($request->lang);
}
return $next($request);
}
}

I was facing the same problem, the locale was changing in session but not in config. So have checked the session's locale in every blade and controller and set the default the language instant from there, here is the code on my blade file
#php
if(\Session::get('locale') == 'en')
\App::setLocale('en');
else
\App::setLocale('bn');
#endphp
Hope it will help you

Related

Laravel 5.4: Passing a variable via Request to controller

Generally speaking this should be a rather simple problem. IT should be very similar to the following question on Stack Overflow
But seeing as it has been two years, maybe some of the syntax has changed.
All I want to do is pass a variable from the middleware to the controller, so I'm not duplicating mysql queries.
Here is my middleware:
namespace App\Http\Middleware;
use Closure;
class CheckRole
{
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle($request, Closure $next)
{
$id = $request->user()->id;
$rr = $request->user()->isSuperAdmin();
if ($request->user()->isSuperAdmin()) {
$request->merge(['group' => 123]);
return $next($request);
}
echo "not admin";
}
}
So the middleware works fine and if I DD($request) on the middleware I see my group => 123 on the page. (Right now it's 123 for the sake of simplicity.)
So I want to pass it to my AdminController:
<?php
namespace SleepingOwl\Admin\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
use SleepingOwl\Admin\Form\FormElements;
use SleepingOwl\Admin\Form\Columns\Column;
use SleepingOwl\Admin\Display\DisplayTable;
use Illuminate\Contracts\Support\Renderable;
use SleepingOwl\Admin\Display\DisplayTabbed;
use Illuminate\Validation\ValidationException;
use SleepingOwl\Admin\Contracts\AdminInterface;
use SleepingOwl\Admin\Model\ModelConfiguration;
use Illuminate\Contracts\Foundation\Application;
use SleepingOwl\Admin\Contracts\Form\FormInterface;
use SleepingOwl\Admin\Contracts\ModelConfigurationInterface;
use SleepingOwl\Admin\Contracts\Display\ColumnEditableInterface;
class AdminController extends Controller
{
/**
* #var \DaveJamesMiller\Breadcrumbs\Manager
*/
protected $breadcrumbs;
/**
* #var AdminInterface
*/
protected $admin;
/**
* #var
*/
private $parentBreadcrumb = 'home';
/**
* #var Application
*/
public $app;
/**
* AdminController constructor.
*
* #param Request $request
* #param AdminInterface $admin
* #param Application $application
*/
public function __construct(Request $request, AdminInterface $admin, Application $application)
{
$this->middleware('CheckRole');
So as you can see I call the middleware on this constructor. After calling it I should be able do something like:
$request->get('group'); or $request->group;
After trying for quite a while nothing seems to be working and I keep getting a null value. Fundamentally, this shouldn't be terribly difficult, but I seem to have my syntax off or not using the right name spaces?
Instead of this code line:
$request->merge(['group' => 123]);
You can try:
$request->request->add(['group' => 123]);
What this code line will do is if a parameter named group exists in the $request it will overwrite with the new value, otherwise it will add a new parameter group to the $request
In your controller, you can get the value of group parameter as:
$group = $request->group; OR $group = $request->input('group');
Thanks to the joint help of #Rahul-Gupta and #shock_gone_wild. It was a joint effort I guess.
The first issue is that I'm using sleepingOwl laravel boilerplate. Probably not the best idea for someone new to Laravel. (not new to MVC / PHP).
Based on #shock_gone_wild comment, decide move my test over to a simple controller, and not the sleeping owl nonsense. (they have a lot of code.) Anyways, I believe that helped. I did leave the middleware in the constructor because I didn't apply the middleware to the routes.
Then I followed #Rahul-Gupta syntax.
So here is final result, hopefully this will save someone sometime someday...
namespace App\Http\Middleware;
use Closure;
class CheckRole {
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle($request, Closure $next) {
if ($request->user()->isSuperAdmin()) {
$request->request->add(['group' => 123]);
return $next($request);
} else {
echo "not admin";
}
}
}
Then here is the simple controller.
use Illuminate\Http\Request;
use App\task;
use App\User;
use App\HasRoles;
class TaskController extends Controller {
public function __construct() {
// constructor code...
$this->middleware('auth');
$this->middleware('CheckRole');
}
public function index(Request $request) {
$group = $request->input('group');
echo "---->" . $group;
$tasks = Task::all();
return view('test_task', compact('tasks'));
}
}

how can i detect language in laravel 5.1 api for validation error?

I have a api in laravel and I want return validation errors in user's language. how can I specify language in laravel api?
for example response this :
if ($validator->fails()) {
return response()->json([
'errors' => $validator->getMessageBag()->getMessages(),
], 400);
}
return best for each language. fa and en.
There is No need Of Doing All This
You can Do this in your resources Folder
1)Laravel's localization features provide a convenient way to retrieve strings in various languages, allowing you to easily support multiple languages within your application. Language strings are stored in files within the resources/lang directory. Within this directory there should be a subdirectory for each language supported by the application
For step by step guide check this link : https://laravel.com/docs/5.3/localization
1) create a middleware in App/Http/Middleware
localization.php
and write these in that:
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Foundation\Application;
/**
* Class Localization
*
* #author Mahmoud Zalt <mahmoud#zalt.me>
*/
class Localization
{
/**
* Localization constructor.
*
* #param \Illuminate\Foundation\Application $app
*/
public function __construct(Application $app)
{
$this->app = $app;
}
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
*
* #return mixed
*/
public function handle($request, Closure $next)
{
// read the language from the request header
$locale = $request->header('Content-Language');
// if the header is missed
if(!$locale){
// take the default local language
$locale = $this->app->config->get('app.locale');
}
// check the languages defined is supported
if (!array_key_exists($locale, $this->app->config->get('app.supported_languages'))) {
// respond with error
return abort(403, 'Language not supported.');
}
// set the local language
$this->app->setLocale($locale);
// get the response after the request is done
$response = $next($request);
// set Content Languages header in the response
$response->headers->set('Content-Language', $locale);
// return the response
return $response;
}
}
2) Register the middleware in the Middlewares
for this. go to App\Http\Kernel.php
add in this array that there is in kernel file:
protected $middleware = []
this one.
\App\Http\Middleware\Localization::class,
3) add this to the app.php in config dir
'supported_languages' => ['en' => 'English', 'fa' => 'persian'],
4) create language folder in the lang folder "resources/lang" for your language (in this case it is [fa] next to [en]) and of course set your files there. for this question only copy validation.php file to your fa folder and change error text.
5) set the header "Content-Language" in your request to ([en] or [fa]).

laravel auth middleware not redirectly on intended page

I am using hesto/multi-auth package
as default if i have assigned the auth middleware to a route the so after login it should redirect me back to the intended page but it's doing only the first time..
everything working exactly i want only the first time but once i logout and try to access the route again it does go to login page and than redirects to the user/home, but first time it works perfect see the 40 sec video
http://neelnetworks.org/video/laravel.mp4
any solution for this?
these are my web routes
Route::get('/', 'PagesController#getIndex')->middleware('user');
Route::group(['prefix' => 'user'], function () {
Route::get('/login', 'UserAuth\LoginController#showLoginForm');
Route::post('/login', 'UserAuth\LoginController#login');
Route::post('/logout', 'UserAuth\LoginController#logout');
Route::get('/register', 'UserAuth\RegisterController#showRegistrationForm');
Route::post('/register', 'UserAuth\RegisterController#register');
Route::post('/password/email', 'UserAuth\ForgotPasswordController#sendResetLinkEmail');
Route::post('/password/reset', 'UserAuth\ResetPasswordController#reset');
Route::get('/password/reset', 'UserAuth\ForgotPasswordController#showLinkRequestForm');
Route::get('/password/reset/{token}', 'UserAuth\ResetPasswordController#showResetForm');
});
here is my Pages Controller
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class PagesController extends Controller
{
public function getIndex()
{
return "hello";
}
}
first time it works perfectly why not after we logged in once?
it works again if i clear all my cache and cookies, is this a default behaviour or is this a bug in laravel? can you please clarify or is it a issue with the package
the issue has been raised in github https://github.com/Hesto/multi-auth/issues/46
Make your showLoginForm method like this inside your UserAuth/LoginController.php
public function showLoginForm()
{
session()->put('url.intended',url()->previous());
return view('user.auth.login');
}
Because it changes the previous url when posting form to /user/login and you will be redirected to /user/home if you logged in
after so much of digging i found out the correct solution
in RedirectIfNot{guard-name} eg RedirectIfNotAdmin
we need to add this line
session()->put('url.intended', url()->current());
so the middleware will look like this
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Support\Facades\Auth;
class RedirectIfNotAdmin
{
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle($request, Closure $next, $guard = 'admin')
{
if (!Auth::guard($guard)->check()) {
session()->put('url.intended', url()->current());
return redirect('/admin/login');
}
return $next($request);
}
}
Default redirect for laravel after login is to go to /home set in the LoginController:
use AuthenticatesUsers;
/**
* Where to redirect users after login.
*
* #var string
*/
protected $redirectTo = '/home';
and there is default middleware RedirectIfAuthenticated
class RedirectIfAuthenticated
{
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #param string|null $guard
* #return mixed
*/
public function handle($request, Closure $next, $guard = null)
{
if (Auth::guard($guard)->check()) {
return redirect('/home');
}
return $next($request);
}
}
and in app/Http/Controllers/Auth/RegisterController.php
class RegisterController extends Controller
{
/*
|--------------------------------------------------------------------------
| Register Controller
|--------------------------------------------------------------------------
|
| This controller handles the registration of new users as well as their
| validation and creation. By default this controller uses a trait to
| provide this functionality without requiring any additional code.
|
*/
use RegistersUsers;
/**
* Where to redirect users after login / registration.
*
* #var string
*/
protected $redirectTo = '/home';
So that is where you need to make changes in order to work your way...

New registered user to be redirected to the password reset screen

I'm quite new to Laravel and have been stumped on a problem for 2 days - I'd be grateful for some guidance.
I'm using the default out-of-the-box User authentication system with Laravel 5.3. A new user is created automatically behind the scenes by an existing Admin user - I will in time hide the user registration page. I have also successfully set up middleware to check if a user is newly registered (by looking for a null 'last_logged_in_date' that I've added to the migration).
All I want to happen is for a new registered user to be redirected to the password reset screen that ships with Laravel (again, in time I will create a dedicated page). I would like this to happen within the middleware file. So far, my middleware looks like this:
<?php
namespace App\Http\Middleware;
use Closure;
use App\Http\Controllers\Auth;
class CheckIfNewUser
{
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle($request, Closure $next)
{
$user = $request->user();
if (! is_null($user->last_logged_in_date )) {
return $next($request);
}
// This is where I'm stuck!!!
}
}
I'm not sure what code to enter at the location indicated by the comments above. I've tried sendResetLinkEmail($request); etc and have imported what I though were the correct classes but I always end up with a Call to undefined function App\Http\Middleware\sendResetLinkEmail() message irregardless of what I 'use' at the top of my class.
Where am I going wrong? Thanks!
Well that happens because you have not defined your sendResetLinkEmail($request) function yet. You can do it like this, or you can create a new class with that and then call the class.
Call the trait SendsPasswordResetEmails and then access it with $this since traits are not classes and you cannot access their members directly.
<?php
namespace App\Http\Middleware;
use Closure;
use App\Http\Controllers\Auth;
use Illuminate\Foundation\Auth\SendsPasswordResetEmails;
class CheckIfNewUser
{
use SendsPasswordResetEmails;
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle($request, Closure $next)
{
$user = $request->user();
if (! is_null($user->last_logged_in_date )) {
return $next($request);
}
// This is where I'm stuck!!!
//EDIT
//return $this->SendsPasswordResetEmails->sendResetLinkEmail($request);
return $this->sendResetLinkEmail($request);
}
}

Lavary laravel menu not working

I am using Lavary's Laravel menu package for creating menus which is defined in middleware named frontMenu and applied it using route grouping.However when I access the particular route, it says Class 'App\Http\Middleware\Menu' not found.I have also correctly added content on config/app.php as per documentation.My middleware code is as follows:
<?php
namespace App\Http\Middleware;
use Closure;
use App\Service\PageService;
class frontMenu
{
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle($request, Closure $next)
{
Menu::make('myNavBar', function($menu){
$menu->add('Home');
$menu->add('About', array('route' => 'page.about'));
$menu->about->add('Who are we?', 'who-we-are');
$menu->about->add('What we do?', 'what-we-do');
$menu->add('services', 'services');
$menu->add('Contact', 'contact');
});
return $next($request);
}
}
what have I done wrong ?
I was missing Use Menu;.Thanks #K.Toress for assist

Resources