The laravel application url will be something like app.laravel.com\{clientName}. All the routes will be following the client_name, for example app.laravel.com\{clientName}\home, app.laravel.com\{clientName}\profile. Will load/ render the application depends on the clientName.
routes/web.php
Route::group(['prefix' => '{clientName}', 'middleware' => 'appclient'], function () {
Route::get('/', 'ClientController#index');
Route::post('login', 'Auth\LoginController#login');
Route::post('logout', 'Auth\LoginController#logout');
Route::get('home', 'HomeController#index');
});
In the appclient middleware
public function handle($request, Closure $next) {
$clientName = explode('/', $request->path())[0];
$client = Client::where('clientName', $clientName)->first();
if(!isset($client->id)) {
abort(404);
}
Config::set('session.path', "/$clientName");
return $next($request);
}
What I'm trying to achieve is set the session based on the clientName directory. When I login I'm getting TokenMismatchException.
First question
Can I store the session based on url with directory like app.laravel.com\{clientName} ?
Second Question
I saw there is a setting session.path, what above I tried is to use that approach. If that is possible, how can I fixed this issue? Is it a good idea to updating the session path in the middleware?
Appreciate any feed back or other approaches
UPDATE
Using Redis as session driver
In my further investigation the request session token every time generates new one
What I did is updated the session.path & session.cookie dynamically.
Config::set('session.path', "$clientName");
Config::set('session.cookie', $clientName.'_laravel_session');
This is currently working for me.
Related
I'm trying to make alive again an old project using Laravel 5.4 and Laravel Valet.
I'm facing an issue with authentication.
LoginController
public function authenticated(Request $request, User $user){
$previous_session = $user->session_id;
if ($previous_session) {
Session::getHandler()->destroy($previous_session);
}
$user = Auth::user();
$user->session_id = Session::getId();
$user->save();
Auth::login($user, true);
return redirect('testlogin');
}
Routes
Route::get('testlogin', function () {
dd(\Illuminate\Support\Facades\Auth::check());
});
In the LoginController, $user is retrieved and not null, but as soon as a redirection is made Auth::check() is false
Questions
What's wrong ? I cannot make make up my mind on this
This drove me crazy a few times as well. Most likely your 'testLogin' route is not contained within the auth middleware, which would not give you auth at the time of the route passing. If this is the case, move your 'testLogin' route inside the following:
Route::group(['middleware' => ['auth']], function () { ... HERE ... }
In the .env file, the variable SESSION_DOMAIN was not set properly and did not reflect the local domain (which had changed between now and few years ago)... Stupid error but I hope it might prevent others to do the same.
I'm fairly new to Laravel, so this question may obvious to some.
In the case of running checks per HTTP request, for example User Authentication. Is there a better, more efficient or simple correct way to run these checks. From my initial research it would seem that this could be accomplished using either MiddleWare, eg.
public function __construct()
{
$this->middleware('auth');
}
It also seems like it would be possible using routing groups, eg.
Route::group(['middleware' => 'auth'], function () {
Route::get('/', function () {
// Uses Auth Middleware
});
Route::get('user/profile', function () {
// Uses Auth Middleware
});
});
Is there any benefits of doing this either of these two ways? Apart from the obvious benefit of not having to put $this->middleware('auth'); in every controller auth would need to be checked.
Thanks
Edit..
After taking on your advice I attempted to utilities the route grouping to control my Auth MiddleWare. But this has seemed to have broken my site.
Route::group(['middleware' => 'auth'], function () {
Route::auth();
Route::get('/home', 'HomeController#index');
Route::get ( '/redirect/{provider}', 'SocialAuthController#redirect' );
Route::get ( '/callback/{provider}', 'SocialAuthController#callback' );
});
Am I missing something obvious?
You are almost there, just remove the Route::auth():
Route::group(['middleware' => 'auth'], function () {
Route::get('/home', 'HomeController#index');
//add more Routes here
});
The suggested options did not work for me but when I checked the laravel documentation, I found this:
Route::middleware(['web'])->group(function () {
//Your routes here
});
It works for me. Laravel 8.*
There is no real difference, personally i use groups for the standard middleware and put exceptions in the construct
Using Route group is easy for maintenance/modification , other wise you will have to remember each controller where you are using certain middle ware, of course this not a concern in a small medium sized application, but this will be hard in a large application where is lots of controller and references to middle ware.
Lately I've been working on a project in Laravel 5.2 and now I'm having problems with sessions not persisting. I've read most of the questions already asked regarding this but everyone has the same answer that I have already tried - applying web middleware.
I've read that there was a new L5.2 update where the web middleware group is already applied by default. I checked my routes with php artisan route:list and I can see that every route has only 1 web middleware applied.
I'm creating session with $request->session()->put('key', 'value') but as soon as I comment that line the session is nowhere to be seen anymore.
Edit
I want to set the session inside a controller when I visit a news page, but I tried it on a simple test route as well. Route where I set this is news/{id} and I want to use it on the front page which is in /
I wish to store recently visited pages in session so I can then show it to the user on the front page.
Session config file I left untouched. So it's using file driver
Here is a tested routes to use for your projects
Please use a middleware instead of the function in the routes file
routes.php
// Only as a demo
// Use a middleware instead
function addToSession ($routeName) {
$visited = session()->get('visited', []);
array_push($visited, $routeName);
session()->put('visited', $visited);
}
Route::get('/', function () {
addToSession('/');
return view('welcome');
});
Route::get('/second', function () {
addToSession('/second');
return view('welcome');
});
Route::get('/third', function () {
addToSession('/third');
return view('welcome');
});
Route::get('/history', function() {
return session()->get('visited');
});
The /history route will return a JSON having the history.
I am New in Laravel, and using Laravel 5
I am storing some values in Session like this
This is in a Controller with function say ABC
Session::put('check_in', $check_in);
Session::put('check_out', $check_out);
Session::put('no_of_rooms', $no_of_rooms);
Session::put('adult', $adult);
Session::put('child', $child);
return view('room');
I am getting the values of all these Sessions in rooms view, but now the problem is when I am going to some other link or on other page from this room view and using the Session as
echo Session::get('check_in')."<br>";
echo Session::get('check_out')."<br>";
echo Session::get('no_of_rooms')."<br><br>";
echo Session::get('adult')."<br>";
echo Session::get('child')."<br>";
I am not able to get any of these Sessions value.
I am using Sessions so it has to be on all the pages till the Session flashed or browser gets closed, but its not retrieving any of the Session values..
I have seen may topics like this on Stack Overflow, but I am not able to understand those answers, Please Explain me thoroughly and solve this Problem, I am stucked at this part from last 4 to 5 days clueless.......
If your using Laravel 5.*, then you should use 'web' middleware in all routes to use session.
This looks like this: in routes.php in app/http directory
Route::group(['middleware' => 'web'], function () {
Route::Auth();
Route::get('/', 'HomeController#index');
Route::get('/login', 'UserController#userLoginView');
Route::post('/login', 'UserController#userLogin');
}
You can use session in all those routes by declaring it under 'web' middleware.
I suggest you read more about 'web' middleware in Laravel 5.
Check this out:
My Laravel 5.2.10 Sessions wont persist
NOTE: As of Laravel 5.2.27 the web middleware is now in place by default, Try removing the Route::group and see if that helps. https://github.com/laravel/laravel/blob/v5.2.27/app/Providers/RouteServiceProvider.php#L56
Create a construction __construct() in your controllers that required the user to be connected:
public function __construct()
{
$this->middleware('auth');
}
and this automatically will check if the user is authenticated if not it will redirect them to login page
(I have asked this question before, and did find a way around which worked for a while, but soon got out of hand. So now I am looking for a perfect solution to achieve this, the Laravel way.)
The problem is pretty simple, when admin goes to http://example.com/dashboard they should see the admin dashboard and when manager goes to the same link he should see the managers dashboard.
The way around that I used before was to call the pagecontroller and then depending on the user role call the relevant admin's or manager's dashboard controller.
// ROUTES.php
Route::group(['middleware' => 'auth'], function () {
Route::get('dashboard', 'PagesController#dashboard');
Route::get('users', 'PagesController#manageUsers');
});
// PagesController
public function dashboard(){
if($this->user->isAdmin()){
return $controller = app()->make('App\Http\Controllers\Admin\dashboard')->index();
}
if($this->user->isManager()){
return $controller = app()->make('App\Http\Controllers\Manager\dashboard')->index();
}
}
Now the problem with this approach is that I can no longer call the middleware on the dashboard controller because the process doesn't involve calling the kernel.
I am pretty sure there must be a way to achieve such a basic feature, I would be really grateful if someone can sort this out.
I think the reason this isn't a Laravel default feature because it kinda goes counter to what routes are supposed to represent. In other words, this isn't the Laravel Way. Why not redirect the user depending on their role?
// ROUTES.php
Route::group(['middleware' => 'auth'], function () {
Route::get('dashboard', function() {
if($this->user->isAdmin())
return redirect('/dashboard/admin');
if($this->user->isManager())
return redirect('/dashboard/manager');
return redirect('/home');
});
Route::get('dashboard/admin', 'Admin\dashboard#index');
Route::get('dashboard/manage', 'Manager\dashboard#index');
Route::get('users', 'PagesController#manageUsers');
});