Laravel database session not working when setting a session domain - php

I encounter issues with the database driver in order to store sessions cookies:
The database connection is currently working but cookies are not set in the browser however session data are in my database.
I have run:
php artisan session:table
Set database session in my .env file:
SESSION_DRIVER=database
Bellow the config/session.php file:
[
'driver' => env('SESSION_DRIVER', 'file'),
'connection' => 'mysql',
'table' => 'sessions',
]
EDIT 1:
The route in web.php:
Route::group(['domain' => GetDomainInfo::GetDomainName(), 'middleware' => 'web'], function () {
Route::get('/', "HomeController#index");
});
Solved issue by :
I have created for example a localhost domain: webcv by adding to my hosts file:
127.0.0.1 webcv.local
127.0.0.1 admin.webcv.local
Set the session domain to : .webcv.local in config/session.php like so:
'domain' => env('SESSION_DOMAIN', ".webcv.local"),
Or just by adding in the .env file:
SESSION_DOMAIN=.webcv.local
Now I can access to both webcv.local and admin.webcv.local with the same cookie.

When you work with the database driver for sessions, you have to create the session table.
I'll assume you already scaffold the native authentication system by doing php artisan make:auth and migrated the migrations.
So first you generate the migration, and then migrate:
php artisan session:table
Execute the migration:
php artisan migrate
Obviously, this won't work if the routes you're checking on, aren't using the web middleware.
If you're not registering the routes in /routes/web.php, then you have to manually specify the web middleware for them. Either in your controller's constructor, or directly in the route itself.
Edit after fix for future reference:
Also, check your domain in config/session.php is the same you're using in development or production, depending where you are working on.

Related

Laravel Session Authentication in localhost?

can anyone teach me why i cant authenticate my laravel session iny my localhost? (database driven!)
Im actually using the auth service from breezer.
**
my first question is: is it possible to auth a user on a localhost by laravels sessions authentication? For me it worked only in production.
My Frontend goes with Angular.
My trys to authenticate and log the user with:
Auth::guard('api')->check()
Auth::guard('web')->check()
Auth::guard()->check()
failed all, f.E gives me a null error.
auth defaults runs on:
defaults' => [
'guard' => 'api',
'passwords' => 'users',
],
my ENV datas looks like:
SESSION_DRIVER=database
SESSION_LIFETIME=180
SESSION_DOMAIN=localhost:4200
APP_URL=localhost:8000
APP_ENV=local

How to use Redis with auth::attempt in Laravel?

I'm working on a Laravel project and I want to use Redis to store session data for improved performance. I have set up Redis correctly and it's working fine with basic functionality. However, I'm having trouble getting the auth::attempt function to work with Redis.
Here's my current auth::attempt code:
if (Auth::attempt(['email' => $email, 'password' => $password])) {
// User authentication successful
} else {
// User authentication failed
}
This works fine with the default session driver in Laravel, but I want to use Redis for better performance. I have tried changing the SESSION_DRIVER variable in my .env file to 'redis' and set the Redis connection in config/database.php, but I'm still getting an authentication error.
I'm not sure what I'm missing. Can anyone help me understand how to use Redis with auth::attempt in Laravel? Thanks in advance!
When using Redis for session storage in Laravel, you need to ensure that your Redis server is running and that your Laravel application is configured to use Redis as the session driver.
To set Redis as your session driver, you can change the value of the SESSION_DRIVER variable in your .env file to redis. You can also configure the Redis connection in the config/database.php file. Here's an example configuration:
'redis' => [
'driver' => 'redis',
'connection' => 'default',
'table' => 'sessions',
'expire_on_close' => false,
],
Once you've configured Redis as your session driver, you can use the Auth::attempt method as usual. However, if you're still encountering authentication errors, there are a few things you can try:
Make sure your Redis server is running and accessible from your
Laravel application.
Check your Redis configuration in the config/database.php file to
ensure that it's set up correctly.
Clear your Laravel application's cache using the php artisan
cache:clear command.
Check your Redis server's logs for any errors or issues that might
be causing the authentication failures.

HTTP request from a Laravel app on one Apache virtual host to a Lumen app on sibling virtual hosts: MySQL Access denied for user 'root'#'localhost' [duplicate]

I am developing an API service that another site I've developed will be using. So locally when building and testing, obviously I want both local copies of the site to work. However, it seems to mix up the environment variables.
For example:
Site A has APP_URL=http://a.local
Site B has APP_URL=http://b.local
I send a GET Request (using Guzzle) from Site A code to http://b.local/test
The /test endpoing in Site B simply dumps out dump(env('APP_URL'))
Result retrieved by Site A is "http://a.local"
Expected result: "http://b.local"
So the code in Site B is running with environment variables loaded from Site A. This is an issue as Site B cannot access the correct database, it's trying to use the Site A's database.
Is this an issue with my local setup (Win10 + WAMP), PHP settings, Laravel settings?
I also encountered this issue, and it is mentioned here. The resolution for it is to run php artisan config:cache in both projects to cache configuration from .env files or patch the code from here.
are you using artisan commands to run both projects with different ports ?
php artisan serve --port=8000
php artisan serve --port=8010
You can set Environment variables in either the vhost config OR in an .htaccess file:
SetEnv APP_URL http://b.local
Apart from #Daniel Protopopov answer above there is also another way, that is also works when both Site A and Site B are Lumen.
In short just rename your DB_DATABASE variable on each side to a different name. Then change the respective variable names in the respective config/<configfilename>.php files.
So that on Site A you would have SITE_A_DB_DATABASE in .env and matching 'database' => env('API_A_DB_DATABASE', 'forge'), line in config/database.php.
Then your Site B SITE_B_DB_DATABASE will not be overwritten due to variable names are different.
The same solution applies for any .env variables which names match.
Because the command php artisan config:cache doesn't work here (closure needed in routes file config file)
LogicException : Your configuration files are not serializable.
I add phpdotenv with composer :
composer require vlucas/phpdotenv
And at the begginning of the file "/bootstrap/app.php" (after "new Illuminate\Foundation\Application"), I add :
$app->detectEnvironment(function () {
$dotenv = Dotenv\Dotenv::create(__DIR__ . '/../', '.env');
$dotenv->overload();
});
Maybe an alternative
If you are calling a Lumen 8 API from within a Laravel 6 application using GuzzleHttp and the Laravel env is being inherited to Lumen, creating config file worked for me.
In bootstrap/app.php comment below lines to prevent loading current env values from Laravel
// (new Laravel\Lumen\Bootstrap\LoadEnvironmentVariables(
// dirname(__DIR__)
// ))->bootstrap();
In bootstrap/app.php add below line after $app has been created.
$app->configure('database');
Create config/database.php in lumen root folder. Return all env values needed for Lumen api in an array in the config file.
<?php
return [
'timezone' => 'UTC',
'default' => 'pdbmysql',
'connections' => [
'pdbmysql' => [
'driver' => 'mysql',
'host' => 'localhost',
'port' => '3306',
'database' => 'db2',
'username' => 'root',
'password' => 'root',
],
],
];

WAMP Laravel - Sending API requests from one local site to another mixes up environment variables

I am developing an API service that another site I've developed will be using. So locally when building and testing, obviously I want both local copies of the site to work. However, it seems to mix up the environment variables.
For example:
Site A has APP_URL=http://a.local
Site B has APP_URL=http://b.local
I send a GET Request (using Guzzle) from Site A code to http://b.local/test
The /test endpoing in Site B simply dumps out dump(env('APP_URL'))
Result retrieved by Site A is "http://a.local"
Expected result: "http://b.local"
So the code in Site B is running with environment variables loaded from Site A. This is an issue as Site B cannot access the correct database, it's trying to use the Site A's database.
Is this an issue with my local setup (Win10 + WAMP), PHP settings, Laravel settings?
I also encountered this issue, and it is mentioned here. The resolution for it is to run php artisan config:cache in both projects to cache configuration from .env files or patch the code from here.
are you using artisan commands to run both projects with different ports ?
php artisan serve --port=8000
php artisan serve --port=8010
You can set Environment variables in either the vhost config OR in an .htaccess file:
SetEnv APP_URL http://b.local
Apart from #Daniel Protopopov answer above there is also another way, that is also works when both Site A and Site B are Lumen.
In short just rename your DB_DATABASE variable on each side to a different name. Then change the respective variable names in the respective config/<configfilename>.php files.
So that on Site A you would have SITE_A_DB_DATABASE in .env and matching 'database' => env('API_A_DB_DATABASE', 'forge'), line in config/database.php.
Then your Site B SITE_B_DB_DATABASE will not be overwritten due to variable names are different.
The same solution applies for any .env variables which names match.
Because the command php artisan config:cache doesn't work here (closure needed in routes file config file)
LogicException : Your configuration files are not serializable.
I add phpdotenv with composer :
composer require vlucas/phpdotenv
And at the begginning of the file "/bootstrap/app.php" (after "new Illuminate\Foundation\Application"), I add :
$app->detectEnvironment(function () {
$dotenv = Dotenv\Dotenv::create(__DIR__ . '/../', '.env');
$dotenv->overload();
});
Maybe an alternative
If you are calling a Lumen 8 API from within a Laravel 6 application using GuzzleHttp and the Laravel env is being inherited to Lumen, creating config file worked for me.
In bootstrap/app.php comment below lines to prevent loading current env values from Laravel
// (new Laravel\Lumen\Bootstrap\LoadEnvironmentVariables(
// dirname(__DIR__)
// ))->bootstrap();
In bootstrap/app.php add below line after $app has been created.
$app->configure('database');
Create config/database.php in lumen root folder. Return all env values needed for Lumen api in an array in the config file.
<?php
return [
'timezone' => 'UTC',
'default' => 'pdbmysql',
'connections' => [
'pdbmysql' => [
'driver' => 'mysql',
'host' => 'localhost',
'port' => '3306',
'database' => 'db2',
'username' => 'root',
'password' => 'root',
],
],
];

Redirection to login on user auth with Laravel 5.2

I have a Laravel 5.2 application running ok in the live server. It was also running ok in a Ubuntu 14.04 with Apache server.
Now I am using a MAC so I made a fresh installation of my App using the MAMP PRO application. All is runing ok in Frontend but when I try to login to the backend there is a redirection that doesn't allow me to be authenticated. The DB is exactly the same, so the user should be authenticated.
When I type user and password and the hit send the screen shows:
Redirecting to http://localhost/admin/dashboard
Then the screen refresh again and shows:
Redirecting to http://localhost/admin/auth/login
I have think that maybe it is related to the Session, but it is stablished to:
'driver' => env('SESSION_DRIVER', 'file'),
So I do not know why this can be a reason. Any idea?
UPDATE - I include a summary of routes.php
This is my routes.php file (chunks of it)
// Admin area
Route::get('admin', function () {
return redirect('/admin/dashboard');
});
Route::group([
'namespace' => 'App\Http\Controllers\Admin',
'middleware' => 'auth.admin',
], function () {
Route::get('admin/dashboard' , 'AdminController#index');
});
Route::get('admin/auth/login', 'App\Http\Controllers\Admin\Auth\AuthController#login');
It sounds like your routes aren't in the web middleware. Make sure all the routes that require cookies or the session are defined like this:
Route::group(['middleware' => ['web']], function() {
Route::get('your-route-here', 'SomeController#method');
});
This is a new feature in Laravel 5.2.

Categories