I have Laravel set up. I am running multiple domains to it. Before yesterday I had one top level domain and a few sub domains. I added another TLD yesterday and everything started working weird. Specifically, when trying to log into the admin section it redirects to the home page. I have one admin but server domains coming to the site. My route group it:
Route::group(['prefix' => 'admin', 'middleware' => 'auth'], function() {
Sometimes is actually brings me into the admin but as soon as I click on a link I get logged out and redirected to the home page. I keep seeing 401 errors in the console as well.
What would cause this?
edit
Route::group(['prefix' => 'admin', 'middleware' => 'auth'], function() {
Route::get('/', 'AdminController#index');
Route::get('/pages', 'AdminController#pages');
Route::get('page/create', 'AdminController#createPagePage');
Route::post('createPage', 'AdminController#createPage');
Route::get('/page/edit/{page_id}', 'AdminController#editPagePage');
Route::post('editPage', 'AdminController#editPage');
});
$redirectTo = '/';
If you are using Linux, try to check the session file permissions and change them so the app can write session keys on that file and if it doesn't work, try to change the session driver to database.
how to change the session driver?
Go to your .env file and change SESSION_DRIVER=file to SESSION_DRIVER=database.
create a session migration: php artisan session:table.
composer dump-autoload.
Finally migrate (php artisan migrate).
Have you setting the SESSION_DOMAIN right?
One thing you may notice is that session isn’t saved when the user is logged-in in one store and goes to another. To fix that issue, we’ll need to add a SESSION_DOMAIN variable to our .env file, for example:
SESSION_DOMAIN=’.example.com’
That’s all, now user session will be shared across all shops/subdomains in our app.
https://medium.com/#maxkostinevich/how-to-build-multi-domain-laravel-application-e6d87d5e507b
If you are confident with the domain setup correctly. Please verify these few things.
1. Your config/session.php is correctly setup to support multiple domains.
'driver' => env('SESSION_DRIVER', 'file'), // check /storage folder writtable recursivelly.
'domain' => env('SESSION_DOMAIN', null), // verify if single domain is not given in .env or in settings.
'same_site' => null // it should not be strict if you have ajax request across these domain. I mean from javascript you may try to request to other domain.
etc...
2. Confirm, if your routes are not group under domain specific. something like:
Route::group(['domain' => 'xxx'], function($params)
{
// your routes..
});
3. If there is any hardcoded domain verification/conditions or redirection added in code.
4. Any values in .env poiting to single domain.
5. Also don't forgot to clear the cache/compiled view/routes and delete the temp files once. like generated files inside /app/bootstrap & /storage
// Clear Application Cache
php artisan cache:clear
// Clear route cache
php artisan route:cache
// Clear config cache
php artisan config:cache
// Clear compiled view files
php artisan view:clear
6. Any thirdparty package might contains the domain settings. Make sure to verify the files in your /config folder.
7. Check the url rewrite settings in .htaccess
8. Do confirm if there is any proxy settings are there or any software installed on server - very rare case.
In case still having issue, please restart the apache/nginx service once because sometimes the config changes not effected after change that might need server restart.
Hopefully it helps.
Related
I have had some weird issues in the past with Laravel routing, however they could usually be fixed with some form of logical solution, eg. clearing the route cache, or a genuine user error...
But this one is very strange. I have been developing this site for a few weeks and using the /admin routes for some time, but today anything related to /admin or logging in is resulting in a 404 | not found from Laravel. And now even adding any new routes is not working, including very basic ones.
eg. the home page is routed like this:
Route::get('/', [App\Http\Controllers\FrontendController::class, 'home'])->name('home');
But adding:
Route::get('/test', [App\Http\Controllers\FrontendController::class, 'home'])->name('test');
To my web.php routes is also bringing me to a 404.
Just to explain my development environment, I am on Windows and I have tried serving this with both "php artisan serve", and also with XAMPP, but both are giving me the same issue. I won't bother explaining the XAMPP set up, because this was literally working yesterday and nothing has changed, but with php artisan serve it takes me to "http://127.0.0.1:8000/".. this doesn't require any special hacking.. it usually just works.
What have I done differently today?
So all I have done today is:
Added a new command with "php artisan make:command SomeCommandIStartedMaking"
This surely hasn't screwed anything up? I've even deleted the command and reset to my last commit just in case and still the routes are screwed.
In my windows "hosts" file I added "127.0.0.1 somedomain.com"
So this sounds like the kind of thing that would have an effect on routing, and it's where I first noticed the issue.. but since then I have "ipconfig /flushdns", I have removed the entries from my host file, and I have cleared my laravel routes and caches, but still the issue remains.
I am really stuck on this one. Also finally! I have done a route:list and I can clearly see the routes showing up like expected, but I can assure you that nothing has changed since yesterday so this seems like another issue.
Here is a dump of web.php, because I know this will be asked for:
<?php
use Illuminate\Support\Facades\Route;
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
// Frontend
Route::get('/', [App\Http\Controllers\FrontendController::class, 'home'])->name('home');
Route::get('/instagram-gallery', [App\Http\Controllers\FrontendController::class, 'instagramGallery'])->name('instagram-gallery');
Route::get('/{pageAlias}', [App\Http\Controllers\PageController::class, 'index'])->name('page');
Route::post('/contact-send', [App\Http\Controllers\PageController::class, 'contactSend'])->name('contact-send');
Route::get('/test', [App\Http\Controllers\FrontendController::class, 'home'])->name('test');
// Admin
Route::group(['prefix' => 'admin', 'middleware' => ['auth', 'is_admin']], function(){
Route::get('/', [App\Http\Controllers\AdminController::class, 'index'])->name('admin');
Route::get('/search/{table}', [App\Http\Controllers\AdminController::class, 'search'])->name("admin-search");
Route::get('/browse/{table}', [App\Http\Controllers\AdminController::class, 'browse'])->name("admin-browse");
Route::get('/create/{table}', [App\Http\Controllers\AdminController::class, 'create'])->name("admin-create");
Route::get('/edit/{table}/{id}', [App\Http\Controllers\AdminController::class, 'edit'])->name("admin-edit");
Route::get('/manage-account', [App\Http\Controllers\AdminController::class, 'manageAccount'])->name("admin-manage-account");
Route::get('/documentation/{subject?}', [App\Http\Controllers\AdminController::class, 'documentation'])->name("admin-documentation");
Route::post('/create/{table}/action', [App\Http\Controllers\AdminController::class, 'createAction'])->name("admin-create-action");
Route::post('/edit/{table}/{id}/action',[App\Http\Controllers\AdminController::class, 'editAction'])->name("admin-edit-action");
Route::post('/delete', [App\Http\Controllers\AdminController::class, 'deleteAction'])->name("admin-delete-action");
Route::post('/wysiwyg-upload', [App\Http\Controllers\AdminController::class, 'wysiwygUpload'])->name("wysiwyg-upload");
Route::post('/manage-account-action', [App\Http\Controllers\AdminController::class, 'manageAccountAction'])->name("admin-manage-account-action");
});
require __DIR__.'/auth.php';
One thing to add, is that "/contact" resolves just fine which is using the '/{pageAlias}' route as shown above, so some are working and some aren't. How should I trouble shoot this I don't even know where to start :(
Any help would be hot! This is so frustrating haha! Thanks in advance..
This might due to cache so run following commands
php aritsan config:clear
php artisan route:clear
To use single command:
PHP artisan optimize
The problem is the order of your routes - the code will run line by line trying to find a matching route.
Once it hits
Route::get('/{pageAlias}', [App\Http\Controllers\PageController::class, 'index'])->name('page');
It will match /test and naturally stop - never reaching your next route.
To solve this, your specific route /test needs to be defined before your general "catch-all" route /{pageAlias}
I have previously transferred laravel from server to another by copying the laravel project folder, now when i try to login using default laravel auth page , if i enter wrong auth value i get error auth.failed
but when i enter a valid auth value the page refresh but nothing happen.
I notice from browser view source the value of CSRF token is changing one i enter the valid auth value
I tried to delete the session files /storage/framework/sessions
and tried
php artisan view:clear
php aritsan cache:clear
but nothing happen.
How can i fix this issue.
Use Laravel Debugbar for easily debugging such kind of cases.
It's good, simple and sweet ^
I fixed the issue.
In the previous server i was using SSL for my domain so the cookies setting in /config/session.php was true:-
'secure' => env('SESSION_SECURE_COOKIE', true),
Since, the current new server i am not using https when i open my website, so i set the value to false
'secure' => env('SESSION_SECURE_COOKIE', false),
Now everything working fine.
I have a problem. I have 2 computers, the first is Ubuntu and the second is Windows 10. Both computers have a bundle of Vagrant + VirtualBox + Homestead. On a computer with Ubuntu, everything works fine, and on a computer with Windows 10 when I try to send a form to the server, I get the status 419 and the message:
The page has expired due to inactivity. Please refresh and try again.
The CSRF token is updated every time the page is refreshed. This is a clean installation of Laravel + php artisan make:auth and php artisan migrate (default tables) in the clean Homestead environment on both PC. The rights to the session directory are full, the user is vagrant, the group is vagrant. Session file is created..env files are identical (standard), except for the name of the database. What could be the problem? I really need your help!
All the advice on a similar problem did not help me. Cache view, config, etc. i cleaned, the key generated anew. The browser cache was cleaned, cookies checked - on the spot. The only difference between the two computers is the operating system, but does it matter when Laravel is on the Homestead virtual machine?
From your video, change the APP_NAME in your .env file to something other than ‘Laravel’.
I would bet, you have other sites running under the same local URL that have the same APP_NAME.
Changing the APP_NAME changes the session cookie name in config/sessions.php
'cookie' => env(
'SESSION_COOKIE',
str_slug(env('APP_NAME', 'laravel'), '_').'_session'
),
You can manually override the cookie name by setting the SESSION_COOKIE variable in your .env file OR let it fallback to the calculated slug above that utilizes the app name (2nd parameter).
Google Chrome is the only browser this happens in for some reason. I spent almost a year trying to figure this problem out and this was the solution!
Add the route entry in app/Http/Middleware/VerifyCsrfToken.php
protected $except = [
'your/route'
];
If you have already included the CSRF token in your form. Then you are getting the error page possibly beacuse of cache data in your form. Open your terminal / command prompt and run these commands in your project root.
php artisan cache:clear
php artisan config:clear
php artisan route:clear
php artisan view:clear
Also try to clear the browser cache along with running these commands.
Make sure the session secure value in file app / config / session.php is set to null.
'secure' => env('SESSION_SECURE_COOKIE', false),
Is there any possibility to turn on and turn off Laravel 5 maintenance without php artisan up and down commands when my website is being hosted ?
What I've done:
Route::get('site/shutdown', function(){
return Artisan::call('down');
});
Route::get('site/live', function(){
return Artisan::call('up');
});
The first route is working fine. But when I call site/live the site still is shuted down. What can cause this problem ?
If your project is already down, you cannot call another function.
What happens after you run php artisan down is that it creates a file named down inside storage/framework. After running php artisan up the file is removed.
You can create the file manually inside storage/framework. It will down your project. When you want to take your project live again, just remove the file.
I think the right answer is missing here..
You could add your route to app/http/middleware/CheckForMaintenanceMode.php
protected $except = [
//here
];
So It never would be off.
when you run artisan down. site is not available so when try to call up, your IP can't access site.
you must call down with your IP exception.
php artisan down --allow=127.0.0.1 --allow=192.168.0.0/16
or add ::1 to local.
to make that in route without command
try to save this command in specific one and call it.
Laravel 8 introduced secret in maintenance mode, in which you can bypass the maintenance mode by providing a secret, then your Artisan::call would work.
You could add your routes to the $except var in CheckForMaintenanceMode middleware to bypass the check. Then your site/live route would work just fine.
In order to make your site live again using an url, you can create a live.php file which you put in laravel's public folder and then visit http://your.domain/live.php .
In the live.php file you need something like this: (check your projects directory structure if you don't use the default public folder!)
<?php
unlink(dirname(__FILE__) . "/../storage/framework/down");
header("Location: your.domain");
die;
just put
Artisan::call('up');
without route function.
Using 5.0
in config/session.php I have set 'domain' => '.example.com' but it is not working. I cannot persist a session on even one domain like this.
My site has many subdomains:
vancouver.example.com
newyork.example.com
etc... they are hosted on the same server and are the same Laravel app (share the same storage directory)
I login with the correct credentials, upon which the app redirects to another page on the site, and I have no session at that point. var_dump(Auth::user()) shows null even though I logged in with the correct credentials.
storage/framework/sessions shows 14 different files there, they are all for me and I cleared them out before I started testing this.
I'll attach my AuthController#postLogin method below, which works fine if session.php 'domain' => null
public function postLogin(Request $request)
{
$this->validate($request, [
'email' => 'required|email', 'password' => 'required',
]);
$credentials = $request->only('email', 'password');
if ($this->auth->attempt($credentials, $request->has('remember'))) {
Session::flash('message', 'You are now logged in.');
Session::flash('status', 'success');
if (str_contains($_SERVER['HTTP_REFERER'], '?goto=')) {
$params = explode('?', $_SERVER['HTTP_REFERER'])[1];
$target = explode('=', $params)[1];
} else {
$target = '/';
}
return redirect($target);
}
return redirect($this->loginPath())
->withInput($request->only('email', 'remember'))
->withErrors([
'email' => $this->getFailedLoginMessage(),
]);
}
Figured it out. Update domain => '.example.com' in session.php and clear the cookies for the site in question.
#gadss
you need to add session table like this
php artisan session:table
composer dump-autoload
php artisan migrate
and change .env to
SESSION_DRIVER=database
also modify config/session.php
'driver' => env('SESSION_DRIVER', 'database') and
'domain' => '.yourdomain.com'
after that clear your browser's cache and cookies.
You'll need to update the session configuration to persist the session in domain-wide including subdomains. Follow the steps given below.
Go to config/session.php and update the domain with prefix . as config => '.your-domain.com'.
Then clear your application cache, Open the Chrome DevTool and Go to Application > Application > Clear Storage. You'll need to clear out the previous cookies also.
run artisan command php artisan config:cache or php artisan config:clear to drop previously cached laravel application configs.
If you are using database as the session driver, You need to create a session table for that. run command php artisan session:table to generate the session table migration and then migrate it using php artisan migrate. Then perform the three steps given above.
With Laravel 8 it becomes more simplier :
Add SESSION_DOMAIN to your .env file :
SESSION_DOMAIN=.yourdomain.tld
Clear configuration cache :
php artisan config:cache
Delete your browser sessions cookies, then session become shared between all your subdomains.
In my case I used to AutoLogin user to subdomain once account is created on www. domain. Worked fine.
Have you tried storing the sessions in the database, memcached, or redis instead of in files? I had a similar situation to yours and storing sessions in the database solved the issue for me.
For some reason Laravel's session driver doesn't handle cross domain sessions correctly when using the file driver.
If someone still gets the problem with subdomain cookie. Try to change Session Cookie Name in config/session.php
If someone needs to sync session in subdomains with different laravel application sharing same database
Follow all the instructions of #Kiran Maniya
Then you have to keep same application name in order to get same session name. Or just change the cookie config in config/session.php
You can hardcode it if keeping same name is not possible.
'cookie' => env(
'SESSION_COOKIE',
Str::slug(env('APP_NAME', 'laravel'), '_').'_session'
)
to something like:
'cookie' => env(
'SESSION_COOKIE',
'session_sharing_application_session'
)