I hope you are the best.
I'm trying to create a multi-language feature in my Laravel app.
but I don't know how to insert Auth::routes in my web routes file to support my multi-language.
this code works for me but Auth::routes links don't set correctly.
the app can identify target language but in Auth::routes() links arent' correctly.
for example, all the page is based on target language but links in the local language. (target is en_us but links in fa_IR)
Route::get('/', function ()
{
// echo "befpreRpikte".$request->cookie('language').'<br/>';
// return ('CookieInRoute\'/\''.request()->cookie('language'));
return redirect(App::getLocale().'/welcome');
})->middleware(CheckLanguage::class);
Route::get('/{locale}',function($locale)
{
return redirect($locale.'/welcome');
});
Route::get('{locale}/welcome',function($locale)
{
//echo('CookieInRoute\'/\''.request()->cookie('language'));
//die(App::getLocale());
return view('welcome');
})->middleware(CheckLanguage::class);
Route::group(['prefix' =>App::getLocale()], function () {
Auth::routes();
// Route::get(App::getLocale().'/login','HomeController#login');
//Route::get('{locale}/home','HomeController#index');
});
and my middle ware is:
public function handle($request, Closure $next)
{
//echo(var_dump(request()->cookie('language')));
//if(empty(request()->cookie('language')))
cookie()->queue('language',$this->checkUserIsoCode($request->path()),60);
App::setLocale($this->checkUserIsoCode($request->path()));
// dd(request()->cookie('language'));
return $next($request);
}
private function checkUserIsoCode($path)
{
// echo '<br/> <c> c</c></br>';
$available_locales=config('app.all_locales');
if($path==null || $path=="/")// => "/" in addressbar
{
try
{
$userLocale=\Location::get(request()->ip())->countryCode;
}
catch(Exception $e)
{
$userLocale="fa_IR";
}
}
else
$userLocale=$path[0];//locale =>/locale/address
foreach($available_locales as $locale)
{
if(strpos($locale,$userLocale)!==false)//if $locale contain userlocale
{
$userLocale=$locale;
break;
}
}
if(!in_array($userLocale,$available_locales,TRUE))
$userLocale=config('app.fallback_locale');
return $userLocale;
}
You could group all your routes so all of them get locale as prefix:
Route::group(['prefix' => '{locale}'], function() {
Route::get('/', function () {
return view('welcome');
});
Auth::routes();
Route::get('/home', 'HomeController#index')->name('home');
})->middleware(CheckLanguage::class);
This blog post seems to solve what you are trying to do:
https://laraveldaily.com/multi-language-routes-and-locales-with-auth/
Related
I have a signup route. After it register on step1, it emails to the user to verify his account and have a link on his email. After clicking the link, it should redirect to signup/step2, and finished and he can access the job-seeker/home.
so the logic is after finished the registration, user cannot visit again to signup/step2 cause user already finished fill up the form.
and before fillup signup/step2, he can't access also the job-seeker/home. So it's vice versa.
basically my middleware was first: check if the user completed the step2 and added true on column is_completed in database. then on the second middleware is to visit only his route by his role, he can't access other routes from other role and redirect to his home based on his role.
But it throws me too many redirect and switching both side even I still didn't fill up the step2 yet. this is my gif below.
MyCode
Kernel.php
class Kernel extends HttpKernel
{
...
protected $routeMiddleware = [
...
'verified' => \Illuminate\Auth\Middleware\EnsureEmailIsVerified::class,
'isCompleted' => \App\Http\Middleware\IsCompleted::class,
];
Middleware/IsCompleted.php
class IsCompleted
{
public function handle($request, Closure $next)
{
if(auth()->user()->isCompleted == 1){
return $next($request);
}
// if 0, redirect to step2
return redirect()->route('register.step2');
}
Middleware/RedirectIfAuthenticated.php
use Illuminate\Support\Facades\Auth;
class RedirectIfAuthenticated
{
public function handle($request, Closure $next, $guard = null)
{
if (Auth::guard($guard)->check()) {
if ( Auth::user()->hasRole('job-seeker') ) {
return redirect()->route('job-seeker.home');
} else if(Auth::user()->hasRole('admin')) {
return redirect()->route('admin.home');
}
}
return $next($request);
Routes/Web.php
<?php
Route::get('/', function () {
return view('welcome');
});
Route::group(['middleware' => ['verified', 'isCompleted']], function() {
Route::group(['prefix' => 'admin', 'name' => 'admin.'], function() {
Route::get('/home', function(){ return "test"; })->name('admin.home');
});
Route::group(['prefix' => 'job-seeker', 'name' => 'job-seeker.'], function() {
Route::get('/home', 'Jobseeker\HomeController#index')->name('job-seeker.home');
});
});
Auth::routes(['verify' => true, 'register' => false]);
Route::get('signup/{usertype}' , 'Auth\RegisterController#getStep1')->name('register.step1');
Route::post('signup/{usertype}' , 'Auth\RegisterController#postStep1');
Route::group(['middleware' => ['auth']], function() {
Route::get('signup/step2' , 'Auth\RegisterController#getStep2')->name('register.step2');
Route::post('signup/step2' , 'Auth\RegisterController#postStep2');
});
EDIT 1
I inspect the page and go to network tab, and this is the result.
your RedirectIfAuthenticated keeps redirecting all the time. It doesn't ever get to $next($request) for Authenticated User.
You need to have some logic like
if (route is seeker.home and user can visit seeker.home) {
return $next(request);
}
instead of
return redirect()->route('job-seeker.home');
I am experiencing this error when trying to navigate to "/admin". Other routes such as "/employee" are working fine.
Here are my current web routes
Auth::routes();
/* Voyager Routes */
Route::group(['prefix' => 'admin'], function () {
Voyager::routes();
...
});
/* Badge App Routes - All the dashboard routes for managers, employees and HRs are defined here */
Route::group(['middleware' => 'auth', 'prefix' => 'employee'], function () {
Route::get('/', 'frontend\DashboardController#index')->name('homepage');
Route::get('dashboard', 'frontend\DashboardController#index')->name('homepage');
...
});
Route::group(['middleware' => 'auth'], function () {
Route::resource('team-manager', 'frontend\TeamManagerController');
Route::resource('badges', 'backend\BadgeController');
Route::get('badges/award/{id?}', 'backend\BadgeController#award');
Route::post('store_award', 'backend\BadgeController#storeAward')->name('store_award');
});
/* User Redirector - Based on user role */
Route::group(['middleware' => ['redirector']], function () {
Route::get('/');
Route::get('login');
});
And here's my middleware redirector
public function handle($request, Closure $next){
if (!Auth::guest()) {
$user = User::find(Auth::id());
// TODO: fix static id below
return $user->role_id == 1 ? redirect('admin') : redirect('employee');
}
return redirect(route('voyager.login'));
}
Thank you in advance!
The problem is in your middleware:
return $user->role_id == 1 ? redirect('admin') : redirect('employee');
You have admin role, and you are also in /admin page. Then your middleware redirects you again and again to /admin.
It is better to check if the user is not in the /admin or /admin/* related routes, then redirect him to admin.
if($user->role_id == 1) {
//check if user is in /admin or /admin related routes.
return ($request->is('/admin') or $request->is('/admin/*')) ? $next($request) : redirect('admin');
} else {
redirect('/employee');
}
Im a Laravel noob, I have a question regarding my Laravel code. It registers successfully, and saves the web session when registering, but not when logging in. It works fine with the login, when I entered a wrong password on purpose, the correct action is happenning, and also when I log in correctly. But When I log in, it doesnt save the session at all, its empty. Please take a look:
My UserController function for logging in:
public function processLogin(Request $request)
{
if (Auth::attempt(['email' => $request['email'], 'password' => $request['password'] ], true))
{
Auth::login(Auth::user());
return redirect()->to('/');
}
else
{
return redirect()->back();
}
}
and my routes file:
Route::group(['middleware' => 'web'], function () {
Route::auth();
Route::get('/', function () {
print_r(Session::all());
if (Auth::check()) {
$user = Auth::user();
print_r($user);
} else {
echo 'Guest';
}
return view('welcome');
});
Route::prefix('welcome')->group(function () {
Route::get('about', 'WelcomeController#about');
Route::get('features', 'WelcomeController#features');
Route::get('pricing', 'WelcomeController#pricing');
Route::get('help', 'WelcomeController#help');
});
Route::prefix('user')->group(function () {
Route::get('login', 'UserController#login');
Route::post('login', 'UserController#processLogin');
Route::get('register', 'UserController#register');
Route::post('register', 'UserController#processRegister');
Route::get('logout', 'UserController#processLogout');
});
});
Auth::routes();
I guess you should empty you users table and try this command :
php artisan make:auth
It`s work for me .
In RouteServiceProvider I have:
$router->bind('user', function ($value) {
return app(UserInterface::class)->findOrFail($value);
});
and url for admin is "/admin/user/1".
but for frontend url is "/user/username"
So I want to check if this is "admin" or "frontend" url and for admin bind user but for frontend don't bind user:
$adminRoute = //check if this is admin or frontend url ("/admin/user/1" or "/user/username")
if($adminRoute){
$router->bind('user', function ($value) {
return app(UserInterface::class)->findOrFail($value);
});
}else{
//nothing
}
PS. I don't want change findOrFail() function to find user by username I want disable binding for non admin urls.
Try this:
Route::group(array('prefix' => 'admin'), function() {
$router->bind('user', function ($value) {
return app(UserInterface::class)->findOrFail($value);
});
});
I'm trying to make some custom filters for my Laravel application.
In filter.php I have
Route::filter('admin', function()
{
if (Auth::guest() AND ! Auth::user()->isAdmin()) {
return 'Not Authorized';
}
});
User.php model
public function isAdmin()
{
if($this->role==1) return true;
else return false;
}
And finally in the Route:
//SECTIONS ONLY FOR ADMIN
Route::group(array('prefix' => 'admins', 'before' => array('admin')), function(){
Route::get('/frontoffice', 'FrontofficeController#index');
Route::get('/frontoffice/about', 'FrontofficeController#about');
Route::get('/frontoffice/research', 'FrontofficeController#research');
});
I'm logged in as an Admin in my application, but still I'm getting NotFoundHttpException when I try to access the above URLs in the route.
Any idea why?