Laravel 7 Auth not working on hosted site - php

So I am trying to deploy a Laravel site to bluehost however after successful login which should redirect to '/home' and stop. It instead tries to redirect to '/home' then redirects to '/login'. the same code running on localhost with the same database works fine. Other database operations work fine.
Basically the default auth middleware seems to broken somehow.
I used laravel's built in auth to make make the authentication.
here is the live site:
LoginController.php
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
class LoginController extends Controller
{
use AuthenticatesUsers;
/**
* Where to redirect users after login.
*
* #var string
*/
protected $redirectTo = '/home';
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('guest')->except('logout');
}
}
web.php
<?php
use Illuminate\Support\Facades\Route;
use Illuminate\Support\Facades\Auth;
Route::get('/', 'WelcomeController#index')->name('welcome');
Auth::routes();
// Home
Route::get('/home', 'HomeController#index')->name('home');
//Listings
Route::get('/listings/search', 'ListingController#search')->name('search-listings');
Route::get('/listings/delete/{listing}', 'ListingController#destroy')->name('listing-delete');
Route::resource('listings', 'ListingController');
Route::group(['prefix' => 'messages'], function () {
Route::get('/', ['as' => 'messages', 'uses' => 'MessageController#index']);
Route::get('create', ['as' => 'messages.create', 'uses' => 'MessageController#create']);
Route::post('/', ['as' => 'messages.store', 'uses' => 'MessageController#store']);
Route::get('{id}', ['as' => 'messages.show', 'uses' => 'MessageController#show']);
Route::put('/', ['as' => 'messages.update', 'uses' => 'MessageController#update']);
Route::delete('/', ['as' => 'messages.action', 'uses' => 'MessageController#action']);
});

So it turns out there was a new line before <?php in one of my files in app/config !!
Almost drove me crazy. Worked fine on localhost but not on server. If you encounter this issue, check your .php files for new lines at the beginning of the file.

For me, deleting the files in /bootstrap/cache folder except the .gitignore
then running the command composer dumpautoload worked

Related

Laravel package Controller not found in route

I have a simple package and I want to use the controller. When I try to use it in routes I got
Class App\Http\Controllers\Tropicalista\Admin\Controllers\DashboardController
does not exist
I have this in my /routes/web.php
Route::group([
'namespace' => '\Tropicalista\Admin\Controllers',
'prefix'=> 'admin'], function() {
Route::get('/', ['as' => 'admin.root', 'uses' => 'DashboardController#index']);
});
My controller:
namespace Tropicalista\Admin\Controllers;
use Illuminate\Http\Request;
use Analytics;
use Carbon\Carbon;
use Spatie\Analytics\Period;
use Illuminate\Support\Collection;
use Illuminate\Routing\Controller;
class DashboardController extends Controller
{...}
I think is a namespace problem. So how can I call the package controller?
By default, the RouteServiceProvider includes your route files within
a namespace group, allowing you to register controller routes without
specifying the full App\Http\Controllers namespace prefix. So, you
only need to specify the portion of the namespace that comes after the
base App\Http\Controllers namespace.
You need to remove namespace
Route::group(['prefix'=> 'admin'], function() {
Route::get('/', ['as' => 'admin.root', 'uses' => '\Tropicalista\Admin\Controllers\DashboardController#index']);
});
Since it's a package, you need to register the routes in the package.
You can see an example of registering package controllers here:
$routeConfig = [
'namespace' => 'Barryvdh\Debugbar\Controllers',
'prefix' => $this->app['config']->get('debugbar.route_prefix'),
'domain' => $this->app['config']->get('debugbar.route_domain'),
'middleware' => [DebugbarEnabled::class],
];
$this->getRouter()->group($routeConfig, function($router) {
$router->get('open', [
'uses' => 'OpenHandlerController#handle',
'as' => 'debugbar.openhandler',
]);
});
In order to call package controller, change the namespace group of RouteServiceProvider from
protected $namespace = 'App\Http\Controllers';
to null/empty i.e.
protected $namespace = '';
Then, the route can be written as,
Route::get('homepage', 'Package\Namespace\Controllers\ControllerName#ActionName');
Further, if you want to write route for the default controller, use leading slash '/' before starting url.
Route::get('/homepage', 'App\Http\Controllers\ControllerName#ActionName');
Whether it is good practice or not but it solved the problem.

How do I efficiently override Laravel's generated auth routes?

I have two applications, the routes file of the working one is below:
routes.php
<?php
Route::auth();
Route::group(["prefix" => "api"], function() {
Route::resource("places", "PlacesController");
Route::resource("users", "UsersController");
Route::group(["prefix" => "auth"], function() {
Route::get("/", "AuthController#GetAuth");
Route::get("logout", 'Auth\AuthController#logout');
});
});
Route::get('/', 'RedirectController#toAngular');
I have the same thing in another application but it is not working. I get an InvalidArgumentException because it can't find the login.blade.php file which I deleted because it is handled by Angular. How do I properly and most efficiently override the /login and /register GET routes generated by Route::auth()?
If you want to override /login and /register, you can just add those two routes after declaring Route::auth() like following:
Route::get('login', ['as' => 'auth.login', 'uses' => 'Auth\AuthController#showLoginForm']);
Route::get('register', ['as' => 'auth.register', 'uses' => 'Auth\AuthController#showRegistrationForm']);
As the application can't find the 'login.blade.php' which is actually returned from controller method, not in routes, then you need to override the showLoginForm method in AuthController and return what view you want to load.
public function showLoginForm() {
return view('path.to.your.view');
}

Laravel post route controller method not getting called

I'm building an app in Laravel and I already had my user registration working fine, I now want to modify how the registration works so I modified my route to call a different method.
Originally the route was defined like so:
Route::post('register', 'Auth\AuthController#postRegister');
And this worked fine. I then changed it to:
Route::post('register', 'Auth\AuthController#someOtherMethod');
This method is defined as follows:
public function someOtherMethod(Request $request)
{
die('If the method is called you should see this');
}
However, it doesn't get called (the message doesn't show). Instead it redirects me to the root of the site.
Note that I have a cache-busting script on my server that I run every time I have weird issues like this which runs the following commands:
php artisan route:clear
php artisan cache:clear
service php5-fpm restart
service nginx restart
I also run the page in an incognito/private window every time I make a change.
Now for the interesting part; I tried undoing the changes I made so that it calls postRegister again, I fully expected this to make it revert to the default behaviour but it still redirects me to the root of the site! So now I don't even have a registration page that functions at all.
Does anyone have any idea what's going on?
Thanks in advance for your help.
Edit:
Here's my full routes.php:
use Illuminate\Http\Request;
Route::group(['middleware' => 'web'], function () {
/** Public routes **/
Route::get('', 'HomepageController#index');
Route::get('/', 'HomepageController#index');
Route::get('terms', function() {
return view('terms');
});
Route::get('privacy', function() {
return view('privacy');
});
/** Public auth routes **/
Route::get('register', 'RegistrationController#index');
Route::post('register', 'Auth\AuthController#postRegister');
Route::get('login', function() {
return view('auth.login');
});
Route::post('login', 'Auth\AuthController#postLogin');
Route::get('logout', 'Auth\AuthController#getLogout');
Route::get('dashboard/login', function() {
return view('admin.login');
});
Route::post('dashboard/login', 'AdminAuth\AuthController#postLogin');
Route::get('dashboard/logout', 'AdminAuth\AuthController#getLogout');
/** Admin routes **/
Route::get('dashboard', [
'middleware' => 'admin',
'uses' => 'Admin\DashboardController#index'
]);
Route::get('dashboard/users', [
'middleware' => 'admin',
'uses' => 'Admin\DashboardController#showUsers'
]);
Route::get('dashboard/search', [
'middleware' => 'admin',
'as' => 'adminSearch',
'uses' => 'Admin\DashboardController#query'
]);
/** Admin auth routes **/
Route::get('dashboard/staff/create', [
'middleware' => 'admin',
function () {
return view('admin.register');
}
]);
Route::post('dashboard/staff/create', [
'middleware' => 'admin',
'uses' => 'AdminAuth\AuthController#postRegister'
]);
/** Controllers **/
Route::controllers([
'password' => 'Auth\PasswordController',
]);
});
make sure that you config/auth.php is calling proper Auth guard. Also redirectsTo is by default set to '/' which is route of site. What is in your middleware? the default RedirectIfAuthenticated middleware has by default entry to point to root of the site. Only these 3 scenarios possibly acting other than expected.

Laravel 5.1 - How to set the loginPath in AuthController?

I want to change the default Laravel routes from /auth/login to just /login and vis-à-vis with register.
These are my routes:
Route::get('login', ['as' => 'getLogin', 'uses' => 'Auth\AuthController#getLogin']);
Route::post('login', ['as' => 'postLogin', 'uses' => 'Auth\AuthController#postLogin']);
Route::get('logout', ['as' => 'getLogout', 'uses' => 'Auth\AuthController#getLogout']);
Route::get('register', ['as' => 'getRegister', 'uses' => 'Auth\AuthController#getRegister']);
Route::post('register', ['as' => 'postRegister', 'uses' => 'Auth\AuthController#postRegister']);
Now the problem arises, that when a user tries to access an area that is guarded, the Authentication class kicks in, redirecting the unauthenticated user back to /auth/login instead of just /login.
I though I could solve the problem by setting the $loginPath in my AuthController like this:
protected $loginPath = '/login';
But it seems like the $loginPath is just used for unsuccessful login attempts, instead of unsuccessful authentication attempts, like documented in the AuthenticateUsers Class.
Well I managed to change the redirectURL in the Authenticate Class from this:
return redirect()->guest('auth/login');
to this:
return redirect()->guest('login');
Which solved the issue, yet I would like to set a property for this in my AuthController like this:
protected $redirectIfMiddlewareBlocks = '/login';
For this I check in the Authenticate Class if a property exists, which I set in the AuthController before:
return redirect()->guest(property_exists($this, 'redirectIfMiddlewareBlocks') ? $this->redirectIfMiddlewareBlocks : '/shouldnotbeused');
Yet I get the /shouldnotbeused url, instead of the one set by the redirectIfMiddlewareBlocks property in my AuthController.
How do I set up the path for the login route in my AuthController correctly?
I think the problem is that you are checking the property on the wrong class. You are checking if it exists on $this, which is an instance of Authenticate when it is set on AuthController
So you should change your check to:
property_exists(AuthController::class, 'redirectIfMiddlewareBlocks')
Also, you can't access a protected property from another class. If you want to do that you'll have to make it public. Finally, I would make it static so that you don't have to instantiate an AuthController object to access it. So the final solution is:
class AuthController {
public static $redirectIfMiddlewareBlocks = '/here';
}
And in your Authenticate middleware:
use App\Http\Controllers\AuthController;
class Authenticate {
public function handle() {
return redirect()->guest(
property_exists(AuthController::class, 'redirectIfMiddlewareBlocks')
? AuthController::$redirectIfMiddlewareBlocks
: '/shouldnotbeused'
);
}
}

Laravel 5 can't find class for custom namespace

In my Laravel app I'm splitting the front end and back end code into folder. These are app/Http/Controllers/BackEnd and app/Http/Controllers/FrontEnd. Rather than type all that out on every file I thought it would be easier to define two namespaces, BackEnd and FrontEnd. I've edited my composer file to this:
"autoload": {
"classmap": [
"app/Models",
"database"
],
"psr-4": {
"App\\": "app/",
"BackEnd\\": "app/Http/Controllers/BackEnd",
"FrontEnd\\": "app/Http/Controllers/FrontEnd"
}
},
I then ran composer autodump and set up my route file like this:
Route::group(['prefix' => 'webman', 'middleware' => 'auth', 'namespace' => 'BackEnd'], function()
{
Route::get('/', ['as' => 'webmanHome', 'uses' => 'HomeController#index']);
});
But when I browse to localhost:8000/webman/ I just get an error, Class App\Http\Controllers\BackEnd\HomeController does not exist. The controller does exist, this is the file:
<?php namespace BackEnd;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
class HomeController extends Controller {
/**
* Display the admin home page, showing the front-end menu and "apps" as links to other sections of the ACP.
*
* #param Reqeust $request
*
* #return View
*/
public function index(Request $request)
{
return view('backend.index');
}
}
I've checked vendor/composer/autoload_psr4.php to make sure that the namespace is being defined and it is, this is in the array returned 'BackEnd\\' => array($baseDir . '/app/Http/Controllers/BackEnd'),.
Strangely if I use <?php namespace App\Http\Controllers\BackEnd; at the top of HomeController.php then everything works, why? What am I missing? Why can't autoload find the file with just BackEnd?
When setting namespace in Route::group() it is actually appending that to App\Http\Controllers. What you could do is remove it and reference the full path like so:
Route::group(['prefix' => 'webman', 'middleware' => 'auth'], function()
{
Route::get('/', ['as' => 'webmanHome', 'uses' => '\BackEnd\HomeController#index']);
});
Try changing/commenting the below line in RouteServiceProvider.php
protected $namespace = 'App\Http\Controllers';
There's an interesting and easy way to get around this... Service Providers.
When the route file is loaded via a provider, the 'App\Http...' is not enforced.
public function boot()
{
$this->loadRoutesFrom(app_path('Your/Model/routes.php'));
}
Keep in mind no middleware is attached either. Your route group will have to specify a 'web' middleware or you'll go nuts wondering why validation, etc, isn't working anymore....(been there!)
It's a cool way to go about it anyway, using providers leads to more modular code and re-use.

Categories