session not persisting in laravel - laravel

I use Session in laravel, but when I get session in controller, it's not work.
web.php
Route::get('locale/{locale}',function ($locale){
//Session::put('locale',$locale);
session(['locale' => $locale]);
Session::save();
return redirect()->back();
});
Localization.php
public function handle($request, Closure $next)
{
if(\Session::has('locale')){
\App::setLocale(\Session::get('locale'));
session(['locale' => \Session::get('locale')]);
\Session::save();
}
return $next($request);
}
Kernel.php
protected $middleware = [
\App\Http\Middleware\CheckForMaintenanceMode::class,
\Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
\App\Http\Middleware\TrimStrings::class,
\Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
\App\Http\Middleware\TrustProxies::class,
];
/**
* The application's route middleware groups.
*
* #var array
*/
protected $middlewareGroups = [
'web' => [
\App\Http\Middleware\EncryptCookies::class,
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
\Illuminate\Session\Middleware\StartSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
\App\Http\Middleware\VerifyCsrfToken::class,
\Illuminate\Routing\Middleware\SubstituteBindings::class,
\App\Http\Middleware\Localization::class,
],
'api' => [
\App\Http\Middleware\EventLogMiddle::class,
'throttle:600,1',
'bindings',
],
];
MachCtrl.php (extends Controller)
public function index()
{
$lang = session('locale');
$config = json_encode([
"table" => "Machine_list",
"title" => "machine list",
"rows" => 20,
"column" => [
"Machine_id", "VM_name", "Machine_location","IP_address",
"Network_status", "Current_status"
],
"CUDP" => "0111",
"CreateRoute" => route('machine.create'),
"DeleteRoute" => route('machine.destroy'),
"UpdateRoute" => route('machine.editInfo'),
"locale" => $lang,
]);
return view('table.show')->with(['config' => $config, 'lang' =>
$lang]);
}
I save Session in router and middlemare, it's not work.
But when I put Session in Controller, it's work. As following code:
public function index()
{
session(['locale' => 'en']);
$lang = session('locale');
$config = json_encode([
"table" => "Machine_list",
"title" => "machine list",
"rows" => 20,
"column" => [
"Machine_id", "VM_name", "Machine_location","IP_address",
"Network_status", "Current_status"
],
"CUDP" => "0111",
"CreateRoute" => route('machine.create'),
"DeleteRoute" => route('machine.destroy'),
"UpdateRoute" => route('machine.editInfo'),
"locale" => $lang,
]);
return view('table.show')->with(['config' => $config, 'lang' =>
$lang]);
}
I really want to know what happen in my project.
Thanks.
Edit:
I use dd(session()) in my code:
-web.php
Route::get('locale/{locale}',function ($locale){
Session::put('locale',$locale);
Session::save();
dd(session());
return redirect()->back();
});
Result:
-Localization.php
public function handle($request, Closure $next)
{
if(\Session::has('locale')){
\App::setLocale(\Session::get('locale'));
session(['locale' => \Session::get('locale')]);
//dd(session());
\Session::save();
}
return $next($request);
}
Result:
-MachCtrl.php
public function index()
{
dd(session());
$lang = session('locale');
$config = json_encode([
"table" => "Machine_list",
"title" => "machine list",
"rows" => 20,
"column" => [
"Machine_id", "VM_name", "Machine_location","IP_address",
"Network_status", "Current_status"
],
"CUDP" => "0111",
"CreateRoute" => route('machine.create'),
"DeleteRoute" => route('machine.destroy'),
"UpdateRoute" => route('machine.editInfo'),
"locale" => $lang,
]);
return view('table.show')->with(['config' => $config, 'lang' =>
$lang]);
}
Result:

Try using a different session driver to round down your issue a little bit.
EDIT: Sorry I can't comment yet, <50rep :(

I checked my working code. I set the whole cycle as:
Language middleware:
class Language
{
protected $app;
public function __construct(Application $app, Request $request) {
$this->app = $app;
}
public function handle($request, Closure $next)
{
$this->app->setLocale(session('user_locale', config('app.locale')));
return $next($request);
}
}
In my middleware Kernel.php:
protected $middlewareGroups = [
'web' => [
\Illuminate\Session\Middleware\StartSession::class,
//...
\App\Http\Middleware\Language::class,
]
];
And in route:
Route::get('locale/{locale}',function ($locale){
session(['user_locale' => $locale]);
});

Related

Custom guard and custom provider not working

I created a custom guard with a validate method
public function validate(array $credentials = [])
{
if (!isset($credentials['login']) || empty($credentials['login']) || !isset($credentials['password']) || empty($credentials['password'])) {
return false;
}
$user = $this->provider->retrieveById($credentials['login']);
if (!isset($user)) {
return false;
}
if ($this->provider->validateCredentials($user, $credentials)) {
$this->setUser($user);
return true;
} else {
return false;
}
}
. I also created a custom authorization provider with a validateCredentials method
public function validateCredentials(Authenticatable $user, array $credentials)
{
if ((strcmp($credentials['login'], $this->retrieveByCredentials($credentials)->login) === 0)) {
if (Hash::check($credentials['password'], $user->getAuthPassword())) {
return true;
}
}
return false;
}
. added them to (providers file, code) and to the config/auth
'defaults' => [
'guard' => 'custom',
'passwords' => 'users',
],
'guards' => [
'custom' => [
'driver' => 'custom',
'provider' => 'custom',
]
],
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => App\Models\User::class,
],
'custom' => [
'driver' => 'custom'
],
],
And in AuthServiceProvider:
public function boot()
{
$this->registerPolicies();
Auth::provider('custom', function ($app, array $config) {
return new CustomerAuthProvider($app->make('App\Models\User'));
});
Auth::extend('custom', function ($app, $name, array $config) {
return new CustomAuthGuard(Auth::createUserProvider($config['provider']), $app->make('request'));
});
}
.
In the login controller I check the entered data
if (Auth::validate($attemptData)) {
return response()->redirectToIntended('cabinet');
}
, but for some reason no redirect or authorization occurs.
But if I do this
if (Auth::validate($attemptData)) {
$user = Auth::user();
$id = Auth::id();
dd($user);
return response()->redirectToIntended('cabinet');
}
, then the correct user will be inside it

use laravel jwt authentication only for api without affecting web

I have an issue with authentication in laravel web, I only what to use the JWT authentication for the api only, I notice whenever I change guard in defaults to web 'guard' => 'web' and I try to login with postman using my api it will not work and this error show("message": "Method Illuminate\Auth\SessionGuard::factory does not exist.") but the web will work, if I change it to 'guard' => 'api' I will not be able to login in the web but the api postman login will work.
Only web will work
'defaults' => [
'guard' => 'web',
'passwords' => 'users',
],
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'api' => [
'driver' => 'jwt',
'provider' => 'users',
],
],
Only api will work
'defaults' => [
'guard' => 'api',
'passwords' => 'users',
],
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'api' => [
'driver' => 'jwt',
'provider' => 'users',
],
],
Route
Route::group([
'prefix' => 'auth'
], function () {
Route::post('login', [AuthController::class, 'login']);
Route::post('logout', [AuthController::class, 'logout']);
Route::post('refresh', [AuthController::class, 'refresh']);
Route::post('me', [AuthController::class, 'me']);
});
Controller
class AuthController extends Controller
{
public function __construct()
{
$this->middleware('auth:api', ['except' => ['login']]);
}
public function login(Request $request)
{
$credentials = $request->only('email', 'password');
if ($token = $this->guard()->attempt($credentials)) {
return $this->respondWithToken($token);
}
return response()->json(['error' => 'Unauthorized'], 401);
}
public function me()
{
return response()->json($this->guard()->user());
}
public function logout()
{
$this->guard()->logout();
return response()->json(['message' => 'Successfully logged out']);
}
public function refresh()
{
return $this->respondWithToken($this->guard()->refresh());
}
protected function respondWithToken($token)
{
return response()->json([
'access_token' => $token,
'token_type' => 'bearer',
'expires_in' => $this->guard()->factory()->getTTL() * 60
]);
}
public function guard()
{
return Auth::guard();
}
}
I just want to use JWT authentication for only the api without affecting the web, Thanks
What defaults.guard config does is setting the default guard to be used if none specified.
If you want 2 different authentication methods and guards you should specify each by name in your middlewares.
So instead of Route::middleware('auth')->get(...);
you should write Route::middleware('auth:api')->get(...);
If you want to protect all routes in a group you can do it in app/Http/Kernel.php by adding this lines:
protected $middlewareGroups = [
'web' => [
...
'auth:web'
],
'api' => [
...
'auth:api'
],
];
you can use this
'defaults' => [
'guard' => 'web',
'passwords' => 'users',
],
and in controller where you need api guard use this
auth('api')
for example in login controller
public function login(Request $request)
{
$validator = Validator::make($request->all(), [
'email' => 'required|email',
'password' => 'required|string|min:6',
]);
if ($validator->fails()) {
return response()->json($validator->errors(), 422);
}
if (!$token = auth('api')->attempt($validator->validated())) {
return response()->json(['error' => 'Unauthorized'], 401);
}
$token = auth('api')->claims(['user' => auth('api')->user()])->attempt($validator->validated());
return $this->createNewToken($token);
}
i use this controller and works for me
class UserController extends Controller
{
public function __construct()
{
$this->middleware('auth:api', ['except' => ['login', 'register']]);
}
/**
* Get a JWT via given credentials.
*
* #return \Illuminate\Http\JsonResponse
*/
public function login(Request $request)
{
$validator = Validator::make($request->all(), [
'email' => 'required|email',
'password' => 'required|string|min:6',
]);
if ($validator->fails()) {
return response()->json($validator->errors(), 422);
}
if (!$token = auth('api')->attempt($validator->validated())) {
return response()->json(['error' => 'Unauthorized'], 401);
}
$token = auth('api')->claims(['user' => auth('api')->user()])->attempt($validator->validated());
return $this->createNewToken($token);
// return response()->json([
// 'token' => $this->createNewToken($token),
// ]);
}
/**
* Register a User.
*
* #return \Illuminate\Http\JsonResponse
*/
public function register(Request $request)
{
$validator = Validator::make($request->all(), [
'name' => 'required|string|between:2,100',
'email' => 'required|string|email|max:100|unique:users',
'password' => 'required|string|confirmed|min:6',
]);
if ($validator->fails()) {
return response()->json($validator->errors()->toJson(), 400);
}
$user = User::create(array_merge(
$validator->validated(),
['password' => bcrypt($request->password)]
));
return response()->json([
'message' => 'User successfully registered',
'user' => $user,
], 201);
}
/**
* Log the user out (Invalidate the token).
*
* #return \Illuminate\Http\JsonResponse
*/
public function logout()
{
Auth::logout();
return response()->json(['message' => 'User successfully signed out']);
}
/**
* Refresh a token.
*
* #return \Illuminate\Http\JsonResponse
*/
public function refresh()
{
return $this->createNewToken(auth::refresh());
}
/**
* Get the authenticated User.
*
* #return \Illuminate\Http\JsonResponse
*/
public function userProfile()
{
return response()->json(auth::user());
}
/**
* Get the token array structure.
*
* #param string $token
*
* #return \Illuminate\Http\JsonResponse
*/
protected function createNewToken($token)
{
return response()->json([
'access_token' => $token,
'token_type' => 'bearer',
'expires_in' => auth('api')->factory()->getTTL() * 60,
'user' => auth('api')->user(),
]);
}
}
and routes
Route::prefix('user')->middleware('api')->group(function () {
Route::post('/login', [UserController::class, 'login']);
Route::post('/logout', [UserController::class, 'logout']);
Route::post('/refresh', [UserController::class, 'refresh']);
Route::get('/user-profile', [UserController::class, 'userProfile']);
Route::post('/register', [UserController::class, 'register']);
});

Laravel Localization Routes in Jetstream & Fortify

I am using Laravel 8 with the Jetstream and Fortify authentication module. All the auth module works, on the other hand I was in the process of making the site in multi-languages, and I found myself with errors in authentication.
My problem today is the following, when the user finishes registering, he must check his email, or Laravel tells me the following error :
> Illuminate\Routing\Exceptions\UrlGenerationException
Missing required parameter for [Route: verification.verify] [URI: {locale}/email/verify/{id}/{hash}] [Missing parameter: locale].
But, for the others routes like /en/login, /en/register, /en/user/profile ..., they work fine ! The error is just for the email validation, please help, thanks. To have control over my authentication routes, I ignored the default JetStream & Fortify routes in the app/providers
routes/web.php
<?php
use Illuminate\Support\Facades\Route;
Route::get('/', function(){
return redirect()->route('home-locale', app()->getLocale());
})->name('home');
Route::group([
'prefix' => '{locale}',
'where' => ['locale' => '[a-zA-Z]{2}']], function(){
Route::get('/', 'HomeController#index')->name('home-locale');
Auth::routes();
});
Route::get('/index', 'HomeController#index');
Route::post('/map-agents','MapController#ajaxRequestMap')->name('*','map.agents');
Route::post('/map-agents/agents','MapController#ajaxRequestAgent');
Route::group([
'middleware' => ['auth:sanctum', 'verified'],
'prefix' => '{locale}',
'where' => ['locale' => '[a-zA-Z]{2}']],
function (){
Route::get('/dashboard', 'DashboardController#index')->name('dashboard');
});
Route::group([
'middleware' => ['auth'],
'prefix' => '{locale}',
'where' => ['locale' => '[a-zA-Z]{2}']],
function (){
Route::resource('agents', AgentsController::class);
});
routes/fortify.php
<?php
use Illuminate\Support\Facades\Route;
use Laravel\Fortify\Features;
use Laravel\Fortify\Http\Controllers\AuthenticatedSessionController;
use Laravel\Fortify\Http\Controllers\ConfirmablePasswordController;
use Laravel\Fortify\Http\Controllers\ConfirmedPasswordStatusController;
use Laravel\Fortify\Http\Controllers\EmailVerificationNotificationController;
use Laravel\Fortify\Http\Controllers\EmailVerificationPromptController;
use Laravel\Fortify\Http\Controllers\NewPasswordController;
use Laravel\Fortify\Http\Controllers\PasswordController;
use Laravel\Fortify\Http\Controllers\PasswordResetLinkController;
use Laravel\Fortify\Http\Controllers\ProfileInformationController;
use Laravel\Fortify\Http\Controllers\RecoveryCodeController;
use Laravel\Fortify\Http\Controllers\RegisteredUserController;
use Laravel\Fortify\Http\Controllers\TwoFactorAuthenticatedSessionController;
use Laravel\Fortify\Http\Controllers\TwoFactorAuthenticationController;
use Laravel\Fortify\Http\Controllers\TwoFactorQrCodeController;
use Laravel\Fortify\Http\Controllers\VerifyEmailController;
Route::group([
'middleware' => config('fortify.middleware', ['web']),
'prefix' => '{locale}',
'where' => ['locale' => '[a-zA-Z]{2}']],
function () {
$enableViews = config('fortify.views', true);
// Authentication...
if ($enableViews) {
Route::get('/login', [AuthenticatedSessionController::class, 'create'])
->middleware(['guest'])
->name('login');
}
$limiter = config('fortify.limiters.login');
$twoFactorLimiter = config('fortify.limiters.two-factor');
Route::post('/login', [AuthenticatedSessionController::class, 'store'])
->middleware(array_filter([
'guest',
$limiter ? 'throttle:'.$limiter : null,
]));
Route::post('/logout', [AuthenticatedSessionController::class, 'destroy'])
->name('logout');
// Password Reset...
if (Features::enabled(Features::resetPasswords())) {
if ($enableViews) {
Route::get('/forgot-password', [PasswordResetLinkController::class, 'create'])
->middleware(['guest'])
->name('password.request');
Route::get('/reset-password/{token}', [NewPasswordController::class, 'create'])
->middleware(['guest'])
->name('password.reset');
}
Route::post('/forgot-password', [PasswordResetLinkController::class, 'store'])
->middleware(['guest'])
->name('password.email');
Route::post('/reset-password', [NewPasswordController::class, 'store'])
->middleware(['guest'])
->name('password.update');
}
// Registration...
if (Features::enabled(Features::registration())) {
if ($enableViews) {
Route::get('/register', [RegisteredUserController::class, 'create'])
->middleware(['guest'])
->name('register');
}
Route::post('/register', [RegisteredUserController::class, 'store'])
->middleware(['guest']);
}
// Email Verification...
if (Features::enabled(Features::emailVerification())) {
if ($enableViews) {
Route::get('/email/verify', [EmailVerificationPromptController::class, '__invoke'])
->middleware(['auth'])
->name('verification.notice');
}
Route::get('/email/verify/{id}/{hash}', [VerifyEmailController::class, '__invoke'])
->middleware(['auth', 'signed', 'throttle:6,1'])
->name('verification.verify');
Route::post('/email/verification-notification', [EmailVerificationNotificationController::class, 'store'])
->middleware(['auth', 'throttle:6,1'])
->name('verification.send');
}
// Profile Information...
if (Features::enabled(Features::updateProfileInformation())) {
Route::put('/user/profile-information', [ProfileInformationController::class, 'update'])
->middleware(['auth'])
->name('user-profile-information.update');
}
// Passwords...
if (Features::enabled(Features::updatePasswords())) {
Route::put('/user/password', [PasswordController::class, 'update'])
->middleware(['auth'])
->name('user-password.update');
}
// Password Confirmation...
if ($enableViews) {
Route::get('/user/confirm-password', [ConfirmablePasswordController::class, 'show'])
->middleware(['auth'])
->name('password.confirm');
Route::get('/user/confirmed-password-status', [ConfirmedPasswordStatusController::class, 'show'])
->middleware(['auth'])
->name('password.confirmation');
}
Route::post('/user/confirm-password', [ConfirmablePasswordController::class, 'store'])
->middleware(['auth']);
// Two Factor Authentication...
if (Features::enabled(Features::twoFactorAuthentication())) {
if ($enableViews) {
Route::get('/two-factor-challenge', [TwoFactorAuthenticatedSessionController::class, 'create'])
->middleware(['guest'])
->name('two-factor.login');
}
Route::post('/two-factor-challenge', [TwoFactorAuthenticatedSessionController::class, 'store'])
->middleware(array_filter([
'guest',
$twoFactorLimiter ? 'throttle:'.$twoFactorLimiter : null,
]));
$twoFactorMiddleware = Features::optionEnabled(Features::twoFactorAuthentication(), 'confirmPassword')
? ['auth', 'password.confirm']
: ['auth'];
Route::post('/user/two-factor-authentication', [TwoFactorAuthenticationController::class, 'store'])
->middleware($twoFactorMiddleware);
Route::delete('/user/two-factor-authentication', [TwoFactorAuthenticationController::class, 'destroy'])
->middleware($twoFactorMiddleware);
Route::get('/user/two-factor-qr-code', [TwoFactorQrCodeController::class, 'show'])
->middleware($twoFactorMiddleware);
Route::get('/user/two-factor-recovery-codes', [RecoveryCodeController::class, 'index'])
->middleware($twoFactorMiddleware);
Route::post('/user/two-factor-recovery-codes', [RecoveryCodeController::class, 'store'])
->middleware($twoFactorMiddleware);
}
});
routes/jetstream.php
<?php
use Illuminate\Support\Facades\Route;
use Laravel\Jetstream\Http\Controllers\CurrentTeamController;
use Laravel\Jetstream\Http\Controllers\Livewire\ApiTokenController;
use Laravel\Jetstream\Http\Controllers\Livewire\PrivacyPolicyController;
use Laravel\Jetstream\Http\Controllers\Livewire\TeamController;
use Laravel\Jetstream\Http\Controllers\Livewire\TermsOfServiceController;
use Laravel\Jetstream\Http\Controllers\Livewire\UserProfileController;
use Laravel\Jetstream\Http\Controllers\TeamInvitationController;
use Laravel\Jetstream\Jetstream;
Route::group(
[
'middleware' => config('jetstream.middleware', ['web']),
'prefix' => '{locale}',
'where' => ['locale' => '[a-zA-Z]{2}']],
function () {
if (Jetstream::hasTermsAndPrivacyPolicyFeature()) {
Route::get('/terms-of-service', [TermsOfServiceController::class, 'show'])->name('terms.show');
Route::get('/privacy-policy', [PrivacyPolicyController::class, 'show'])->name('policy.show');
}
Route::group(['middleware' => ['auth', 'verified']], function () {
// User & Profile...
Route::get('/user/profile', [UserProfileController::class, 'show'])
->name('profile.show');
// API...
if (Jetstream::hasApiFeatures()) {
Route::get('/user/api-tokens', [ApiTokenController::class, 'index'])->name('api-tokens.index');
}
// Teams...
if (Jetstream::hasTeamFeatures()) {
Route::get('/teams/create', [TeamController::class, 'create'])->name('teams.create');
Route::get('/teams/{team}', [TeamController::class, 'show'])->name('teams.show');
Route::put('/current-team', [CurrentTeamController::class, 'update'])->name('current-team.update');
Route::get('/team-invitations/{invitation}', [TeamInvitationController::class, 'accept'])
->middleware(['signed'])
->name('team-invitations.accept');
}
});
});
app/Http/Kernel.php
<?php
namespace App\Http;
use Illuminate\Foundation\Http\Kernel as HttpKernel;
class Kernel extends HttpKernel
{
/**
* The application's global HTTP middleware stack.
*
* These middleware are run during every request to your application.
*
* #var array
*/
protected $middleware = [
// \App\Http\Middleware\TrustHosts::class,
\App\Http\Middleware\TrustProxies::class,
\Fruitcake\Cors\HandleCors::class,
\App\Http\Middleware\PreventRequestsDuringMaintenance::class,
\Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
\App\Http\Middleware\TrimStrings::class,
\Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
];
/**
* The application's route middleware groups.
*
* #var array
*/
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,
\Illuminate\Routing\Middleware\SubstituteBindings::class,
\App\Http\Middleware\SetLocale::class,
],
'api' => [
'throttle:api',
\Illuminate\Routing\Middleware\SubstituteBindings::class,
],
];
/**
* The application's route middleware.
*
* These middleware may be assigned to groups or used individually.
*
* #var array
*/
protected $routeMiddleware = [
'auth' => \App\Http\Middleware\Authenticate::class,
'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
'cache.headers' => \Illuminate\Http\Middleware\SetCacheHeaders::class,
'can' => \Illuminate\Auth\Middleware\Authorize::class,
'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
'password.confirm' => \Illuminate\Auth\Middleware\RequirePassword::class,
'signed' => \Illuminate\Routing\Middleware\ValidateSignature::class,
'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
'verified' => \Illuminate\Auth\Middleware\EnsureEmailIsVerified::class,
];
}
app/Http/Middleware/setLocale.php
<?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)
{
$languages = array_keys(config('app.languages'));
$route = $request->route();
if (request('change_language')) {
session()->put('language', request('change_language'));
$language = request('change_language');
if (array_key_exists('locale', $route->parameters) && $route->parameters['locale'] != $language)
{
$route->parameters['locale'] = $language;
if (in_array($language, $languages)) {
app()->setLocale($language);
}
return redirect(route($route->getName(), $route->parameters));
}
} elseif (session('language')) {
$language = session('language');
if (array_key_exists('locale', $route->parameters) && $route->parameters['locale'] != $language && in_array($route->parameters['locale'], $languages))
{
$language = $route->parameters['locale'];
session()->put('language', $language);
}
} elseif (config('app.locale')) {
$language = config('app.locale');
}
if (isset($language) && in_array($language, $languages)) {
app()->setLocale($language);
}
return $next($request);
}
}

Laravel implementing simple MiddleWare doesn't work

In my web application i'm trying to check local in URLs, for example:
In this URL as http://www.sample.com/aboutUs we don't have any locale such as en,ru or etc like: http://www.sample.com/en/aboutUs.
In my web app I implemented simple middleware to check that and fix URL when URLs don't have them:
class language
{
public function handle($request, Closure $next)
{
dd($request);
$locale = $request->segment(1);
if (!array_key_exists($locale, config('app.locales'))) {
$segments = $request->segments();
$segments[0] = config('app.fallback_locale');
return redirect(implode('/', $segments));
}
app()->setLocale($locale);
return $next($request);
}
}
Which that registered into:
protected $middlewareGroups = [
'web' => [
\App\Http\Middleware\Language::class,
...
],
'api' => [
'throttle:60,1',
'bindings',
],
];
protected $routeMiddleware = [
'language' => \App\Http\Middleware\Language::class,
...
];
This middleware only work when we have locale in URL and my code as:
Route::get('/showContent/aboutUs', ['middleware' => 'language', function()
{
dd('asda');
//
}]);
This doesn't work and I don't see any dd output
1:
Route::group(['middleware' => 'web'], function () {
Route::get('/showContent/aboutUs', 'HomeController#aboutUs');
});
2:
Route::group(['middleware' => 'language'], function () {
Route::get('/showContent/aboutUs', 'HomeController#aboutUs');
});
for all my solutions i get this output:
Sorry, the page you are looking for could not be found.

Laravel 5.2 dashboard redirect loop

I am new to laravel and am using the 5.2 version. Through tutorials and such I have found online I have been able to use make:auth for a user account. However I have three different types of users (viewer, artist, sponsor) meaning that each user has to be on their own table and have their own registration. This is a huge project with a ton of registered users each with different options. That being said I am not able to use just one table and create roles it is just to big of a project for that.
I have created two of the three log in systems. The problem I am having is that after the artist is signed in and sent to the artist dashboard I get a :too many redirects” error. The url directs to the correct dashboard but the page does not display. Any help would be much appreciated.
Routes.php
Route::group(['middleware' => ['web']], function () {
Route::get('/', function () {
return view('welcome');
});
Route::get('/artist', function () {
return view('artist');
});
Route::get('/sponsor', function () {
return view('sponsor');
});
Route::get('/viewer', function () {
return view('viewer');
});
Route::get('/contact', function () {
return view('contact');
});
Route::get('/ArtistRegistration', function () {
return view('ArtistRegistration');
});
Route::get('/artdashboard', function () { 'passwords' => [
'users' => [
'provider' => 'users',
'email' => 'auth.emails.password',
'table' => 'password_resets',
'expire' => 60,
],
'artist' => [
'provider' => 'artist',
'email' => 'auth.emails.password',
'table' => 'password_resets',
'expire' => 60,
],
],
];
return view('artdashboard');
});
Route::post('/signup', [
'uses' => 'UserController#postSignup',
'as' => 'signup'
]);
Route::post('/signin', [
'uses' => 'UserController#postSignin',
'as' => 'signin'
]);
Route::get('/dashboard', [
'uses' => 'UserController#getDashboard',
'as' => 'dashboard',
'middleware' => 'auth'
]);
//Route::group(['middleware' => ['artist']], function () {
Route::post('/signupart', [
'uses' => 'ArtistController#postSignupArt',
'as' => 'signupart'
]);
Route::post('/signinart', [
'middleware' => 'artist',
'uses' => 'ArtistController#postSigninArt',
'as' => 'signinart'
]);
Route::group(['middleware' => 'artist', 'as' => 'artdashboard'], function() {
Route::get('artdashboard', 'ArtistController#getArtDashboard');
});
//Route::get('/artdashboard', [
//'uses' => 'ArtistController#getArtDashboard',
//'as' => 'artdashboard',
//'middleware' => 'artist'
// ]);
Auth.php
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'api' => [
'driver' => 'token',
'provider' => 'users',
],
//For Artists
'artist' => [
'driver' => 'session',
'provider' => 'artist',
//'table' => 'artists',
],
],
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => App\User::class,
],
//for Artists
'artist' => [
'driver' => 'eloquent',
'model' => App\Artist::class,
'table' => 'artists',
],
],
Artist.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Contracts\Auth\Authenticatable;
class artist extends Model implements Authenticatable
{
//protected $table = 'artists';
use \Illuminate\Auth\Authenticatable;
}
ArtistController.php
<?php
namespace App\Http\Controllers;
use App\Artist;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
Class ArtistController extends Controller
{
//public function __construct()
//{
//$this->middleware('artist');
//}
public function getArtDashboard()
{
return view('artdashboard');
}
public function postSignupArt(Request $request)
{
$this->validate($request, [
'userName' => 'required|min:4',
'userEmail' => 'required|email|unique:artists',
'userPass' => 'required|min:3',
'first_name' => 'required|max:120',
'last_name' => 'required|max:120',
'zip' => 'required|max:5',
]);
$userName = $request['userName'];
$userEmail = $request['userEmail'];
$userPass = bcrypt($request['userPass']);
$first_name = $request['first_name'];
$last_name = $request['last_name'];
$zip = $request['zip'];
$artist = new Artist();
$artist->userName = $userName;
$artist->userEmail = $userEmail;
$artist->userPass = $userPass;
$artist->first_name = $first_name;
$artist->last_name = $last_name;
$artist->zip = $zip;
$artist->save();
Auth::login($artist);
return redirect()->route('/artdashboard');
}
public function postSigninArt(Request $request)
{
$this->validate($request, [
'userEmail' => 'required',
'userPass' => 'required'
]);
//if (Auth::guard('artist')->attempt($credentials)) {
if (Auth::guard('artist')->attempt(['userEmail' => $request['userEmail'], 'userPass' => $request['userPass']])) {
return redirect()->route('artdashboard');
}
return redirect()->back();
}
}
Middleware\ArtistAuthenticate
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Support\Facades\Auth;
class ArtistAuthenticate
{
/**
* 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 = 'artist')
{
//if ($this->auth->check())
//{
//return new RedirectResponse(url('/artdashboard'));
//}
//return $next($request);
//}
//}
if (Auth::guard($guard)->guest()) {
//if ($this->middleware('guest', ['only'=>['artist', 'viewer', 'sponsor', 'welcome', 'contacts']])
if ($request->ajax() || $request->wantsJson()) {
return response('Unauthorized.', 401);
}//else{
return redirect()->route('artdashboard');
// }
}
return $next($request);
}
}
Kernal.php
protected $routeMiddleware = [
'auth' => \App\Http\Middleware\Authenticate::class,
'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
'artist' => \App\Http\Middleware\RedirectifAuthenticated::class,
'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
//'artist' => \App\Http\Middleware\ArtistAuthenticate::class,
'guest' => \App\Http\Middleware\RedirectifNotArtist::class,
];

Resources