Target class [App\Http\Controllers\Auth\LoginController] does not exist - laravel

I am using Laravel9, trying to seperate frontend and backend. I did many replace, like app\Http change to be app\Frontend\Http or app\Backend\Http.
I did the separation before, it worked. Now I cannot login or logout. But welcome page is ok. Maybe this is because the routes file ?
Auth::routes();
All content of routes/web.php
<?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!
|
*/
Route::group(
[
'prefix' => LaravelLocalization::setLocale(),
'middleware' => [ 'localeSessionRedirect', 'localizationRedirect', 'localeViewPath' ],
], function()
{
Route::get('/', function () {
return view('welcome');
});
Auth::routes();
Route::get('/home', [App\Frontend\Http\Controllers\HomeController::class, 'index'])->name('home');
});
I also did:
composer dump-autoload
php artisan clear-compiled
php artisan route:clear
php artisan cache:clear
not working.
LoginController
<?php
namespace App\Frontend\Http\Controllers\Auth;
use App\Frontend\Http\Controllers\Controller;
use App\Frontend\Providers\RouteServiceProvider;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
class LoginController extends Controller
...

Auth routes of laravel/ui package is kinda hardcoded within AuthRouteMethods class. This is the part of its method from Github repository
$namespace = class_exists($this->prependGroupNamespace('Auth\LoginController')) ? null : 'App\Http\Controllers';
$this->group(['namespace' => $namespace], function() use($options) {
// Login Routes...
if ($options['login'] ?? true) {
$this->get('login', 'Auth\LoginController#showLoginForm')->name('login');
$this->post('login', 'Auth\LoginController#login');
}
// more code
It ensure that Auth routes will be under "default" namespace of Theme\Http\Controllers. But you may change it if wrap it in a group like
Route::group(['namespace' => 'App\Frontend\Http\Controllers'], function () {
Auth::routes();
});
This way you'll prepend group namespace to it so package will find App\Frontend\Http\Controllers\Auth\LoginController class and so on for every other auth controller
Note 1 - all controllers should be under Auth namespace and named specifically as defined in a package, you cannot change it to be like App\Whatever\LoginController or Auth\Whatever\Auth\MyLoginController - but you can do it with App\Whatever\Auth\LoginController
Note 2 - this wouldn't work with uncommented protected $namespace = 'App\\Http\\Controllers'; property within RouteServiceProvider class, as it will prepend namespace twice (you will get something like App\Http\Controllers\App\Frontend\Http\Controllers\Auth\LoginController)

Related

Laravel auth RegisterController namespace causing issue with artisan route:list command [duplicate]

This question already has answers here:
Error “Target class controller does not exist” when using Laravel 8
(27 answers)
Closed 1 year ago.
When I run `php artisan route:list' I get an error it can't find the RegisterController from the auth scaffolding.
Illuminate\Contracts\Container\BindingResolutionException : Target class [App\Http\Controllers\Auth\RegisterController] does not exist.
at C:\xampp\htdocs\antheap\vendor\laravel\framework\src\Illuminate\Container\Container.php:805
801|
802| try {
803| $reflector = new ReflectionClass($concrete);
804| } catch (ReflectionException $e) {
> 805| throw new BindingResolutionException("Target class [$concrete] does not exist.", 0, $e);
806| }
807|
808| // If the type is not instantiable, the developer is attempting to resolve
809| // an abstract type such as an Interface or Abstract Class and there is
Exception trace:
1 Illuminate\Foundation\Console\RouteListCommand::Illuminate\Foundation\Console\{closure}(Object(Illuminate\Routing\Route))
[internal]:0
2 ReflectionException::("Class App\Http\Controllers\Auth\RegisterController does not exist")
C:\xampp\htdocs\antheap\vendor\laravel\framework\src\Illuminate\Container\Container.php:803
Which makes sense considering the RegisterController.php file is in Controllers/Web/Auth/ and its namespace is namespace App\Http\Controllers\Web\Auth;
I'm guessing it's looking for the wrong place because of default routing in the illuminate framework. However all the other Auth controllers are functioning fine. I'm not keen on moving everything just to make the list route:list command happy, though I kinda need it not crashing right now to help fix some other issue.
I've changed the Auth helper in web.php and added the auth routes:
// helper class generating all routes required for user authentication
// (authentication, registration and password resetting)
Auth::routes(['verify' => true, 'register' => false]);
Route::get('/login', 'Auth\LoginController#showLoginForm')->name('login');
Route::post('/login', 'Auth\LoginController#login');
Route::get('/logout', 'LoginController#logout')->name('logout');
Route::group(['middleware' => 'auth'], function () {
Route::get('/password/confirm', 'Auth\ConfirmPasswordController#showConfirmForm')->name('password.confirm');
Route::post('/password/confirm', 'Auth\ConfirmPasswordController#confirm');
});
Route::post('/password/email', 'Auth\ForgotPasswordController#sendResetLinkEmail')->name('password.email');
Route::get('/password/reset', 'Auth\ForgotPasswordController#showLinkRequestForm')->name('password.request');
Route::post('/password/reset', 'Auth\ForgotPasswordController#reset')->name('password.update');
Route::get('/password/password/reset/{token}', 'ResetPasswordController#showResetForm')->name('password.reset');
Route::group(['middleware' => 'guest'], function () {
Route::get('/password/register', 'Auth\RegisterController#showRegistrationForm')->name('register');
Route::post('/password/register', 'Auth\RegisterController#register');
});
However, this still doesn't allow for route:list to work correctly. The weird thing is I can comment out routes from about and they would still work normally (I assume covered by the default ones). Using route:clear doesn't change anything.
I can also add or remove the Auth\ in front of the Controller name, this doesn't keep it from working , nor will it fix route:list
But the app is definitely using it because if I change the URI suffix (like 'login' to 'logintest', it will show that in the browser address.
One thing that I forget to mention is that in RouteServiceProvide.php I added the \Web namespace (I don't know how route:list deals with that?)
/**
* Define the "web" routes for the application.
*
* These routes all receive session state, CSRF protection, etc.
*
* #return void
*/
protected function mapWebRoutes()
{
Route::middleware('web')
->namespace($this->namespace . '\Web')
->group(base_path('routes/web.php'));
}
This because I had to break up the route file at some point into multiple ones with their own namespaces. And I put the Auth inside the Web routes due to many of its routes using limited to no middleware.
Problem is that taking Auth from the web folder and namespace just breaks way more than just route:list.
Ok I solved it, but not in a pretty way by moving back all the auth controllers to the folder route:list was looking for and just adding another separate routing file solely for auth
RouteServiceProvider.php
protected function mapAuthRoutes()
{
Route::middleware('web')
// ->namespace($this->namespace . '\Auth')
->group(base_path('routes/auth.php'));
}
I commented out the \Auth namespace because with testing it didn't seem to work properly
And then routes/auth.php
<?php
use Illuminate\Http\Request;
use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\Artisan;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Route;
use Illuminate\Support\Facades\Session;
/*
|--------------------------------------------------------------------------
| Auth Routes
|--------------------------------------------------------------------------
|
*/
// helper class generating all routes required for user authentication
// (authentication, registration and password resetting)
// Auth::routes(['verify' => true, 'register' => false]);
Route::get('/login', 'App\Http\Controllers\Auth\LoginController#showLoginForm')->name('login');
Route::post('/login', 'App\Http\Controllers\Auth\LoginController#login');
Route::post('/logout', 'App\Http\Controllers\Auth\LoginController#logout')->name('logout');
Route::group(['middleware' => 'auth'], function () {
Route::get('/password/confirm', 'App\Http\Controllers\Auth\ConfirmPasswordController#showConfirmForm')->name('password.confirm');
Route::post('/password/confirm', 'App\Http\Controllers\Auth\ConfirmPasswordController#confirm');
});
Route::post('/password/email', 'App\Http\Controllers\Auth\ForgotPasswordController#sendResetLinkEmail')->name('password.email');
Route::get('/password/reset', 'App\Http\Controllers\Auth\ForgotPasswordController#showLinkRequestForm')->name('password.request');
Route::post('/password/reset', 'App\Http\Controllers\Auth\ForgotPasswordController#reset')->name('password.update');
Route::get('/password/password/reset/{token}', 'App\Http\Controllers\Auth\ResetPasswordController#showResetForm')->name('password.reset');
Route::group(['middleware' => 'guest'], function () {
Route::get('/password/register', 'App\Http\Controllers\Auth\RegisterController#showRegistrationForm')->name('register');
Route::post('/password/register', 'App\Http\Controllers\Auth\RegisterController#register');
});
I had to completely write out the paths for the controllers or it wouldn't work
And the namespace used in the auth controllers (which is also the file path):
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
class LoginController extends Controller
I don't feel like this was the cleanest solution, and I would love to know why route:list doesn't seem to understand the namespacing used before. But at least it's working again now.

Laravel Seperate folders for Web and API Controllers causing error

Im currently trying to create an API for my laravel project,
I have decided to move my API controllers into a subfolder of Controllers. This is the folder structure:
This is the routes file for the api:
<?php
use Illuminate\Http\Request;
use app\Http\Controllers\APIControllers;
/*
|--------------------------------------------------------------------------
| API Routes
|--------------------------------------------------------------------------
|
| Here is where you can register API routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| is assigned the "api" middleware group. Enjoy building your API!
|
*/
Route::group(['prefix' => 'v1'], function() {
Route::get('/event_locations', 'EventLocationsAPIController#all');
});
And this is the EventLocationsAPIController:
<?php
namespace App\Http\Controllers\APIControllers;
use App\EventLocation;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
class EventLocationAPIController extends Controller
{
public function all()
{
$locations = EventLocation::all();
return response()->json($locations);
}
}
When I send an GET request to /api/v1/event_locations I get the following error
Target class [App\Http\Controllers\EventLocationsAPIController] does not exist.
Any help would be appreciated!
You need to declare the namespace in route group as well.
Route::group(['prefix' => 'v1','namespace'=>'APIControllers'], function() {
Route::get('/event_locations', 'EventLocationAPIController#all');
});
you have given EventLocations plural and the controller name is singular EventLocation change the name of the controller as EventLocationAPIController in the route file.
You have to declare your nameaspace on router's group like this:
Route::namespace('APIControllers')->group(function () {
// Controllers Within The "App\Http\Controllers\APIControllers" Namespace
Route::group(['prefix' => 'v1'], function() {
Route::get('/event_locations', 'EventLocationAPIController#all');
});
});
Check Laravel docs for more info.

php artisan route:list ReflectionException class does not exist but its there?

Im having this problem when i use the command said in the title, its not finding my LoginController that i have in my auth folder.
It seams that it wants to load the controller using the wrong path.
Its weird because i never touched or moved anything from that controller i was creating a migration when i notice the error trying the route:list command as for my application it works normally except when i logout it doesn't redirect to my login view anymore it no redirects to public thus showing a 404.
I don't know what i did that it broke those things.
I tried changing the namespace of my controller to the one it shows on the error but its weird because when i change it the new error shows the correct path for the controller but since i changed it does not finds it again.
Also i tried the commands: config:cache, composer dump-autoload, composer update.
This is my controller:
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
class LoginController extends Controller
{
/*
|--------------------------------------------------------------------------
| Login Controller
|--------------------------------------------------------------------------
|
| This controller handles authenticating users for the application and
| redirecting them to your home screen. The controller uses a trait
| to conveniently provide its functionality to your applications.
|
*/
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');
}
}
My web routes:
<?php
Auth::routes();
Route::get('/home', 'HomeController#index')->name('home');
Route::namespace('Admin')->prefix('admin')->middleware(['auth', 'auth.admin'])->name('admin.')->group(function(){
Route::resource('/ImagenAudioVideo', 'PlantillaController', ['except' => ['show', 'create', 'store'] ]);
Route::resource('/Imagen', 'PlantillaImagenesController', ['except' => ['show', 'create', 'store'] ]);
Route::resource('/Audio', 'PlantillaAudiosController', ['except' => ['show', 'create', 'store'] ]);
Route::resource('/Video', 'PlantillaVideosController', ['except' => ['show', 'create', 'store'] ]);
Route::resource('/ImagenAudio', 'PlantillaImagenesAudioController', ['except' => ['show', 'create', 'store'] ]);
Route::resource('/EditarUsuario', 'EditarUsuariosController', ['except' => ['show', 'create', 'store'] ]);
Auth::routes(['register' => false]);
Route::get('/', function () {
return view('home');
});
});
The exception:
ReflectionException : Class App\Http\Controllers\Admin\Auth\LoginController does not exist
at /Applications/MAMP/htdocs/ConfiguradorIEM/vendor/laravel/framework/src/Illuminate/Container/Container.php:790
notice how it shows a different path but when i change the namespace to the path shown in the exception it throws a new error with the previous path.
You have two Auth::routes(); declarations, the second one has the namespace Admin.
This is why you get this error: you have to remove the line Auth::routes(['register' => false]); inside the Admin namespaced Route because you are adding the Admin namespace to all the Auth controllers.
Remember that Auth::routes(); are for the most named routes and the second route declaration override the first one.
If anyone is still searching for a solution for such an error.
In my case, the error showed up only because I forgot to specify the namespace for my controller which was in the Billing directory.
And as soon as I added this line at the top of my controller:
namespace App\Http\Controllers\Billing;
The issue was resolved.

Method App\Http\Controllers\ProductController::getIndex()() does not exist

web.php file
this is my web.php file using laravel 5.4
<?php
/*
|--------------------------------------------------------------------------
| 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!
|
*/
Route::get('/', [
'uses' =>'ProductController#getIndex()',
'as' =>'product.index'
]);
ProductController.php
this is my controller file using laravel5.4
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class ProductController extends Controller
{
//
public function getIndex(){
return view('shop.index');
}
}
How to get rid of this error please help me.
What's wrong with it ?
You shouldn't use () in your route definition. It should be:
Route::get('/', [
'uses' =>'ProductController#getIndex',
'as' =>'product.index'
]);

Laravel Controller Subfolder routing

I'm new to Laravel. To try and keep my app organized I would like to put my controllers into subfolders of the controller folder.
controllers\
---- folder1
---- folder2
I tried to route to a controller, but laravel doesn't find it.
Route::get('/product/dashboard', 'folder1.MakeDashboardController#showDashboard');
What am I doing wrong?
For Laravel 5.3 above:
php artisan make:controller test/TestController
This will create the test folder if it does not exist, then creates TestController inside.
TestController will look like this:
<?php
namespace App\Http\Controllers\test;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
class TestController extends Controller
{
public function getTest()
{
return "Yes";
}
}
You can then register your route this way:
Route::get('/test','test\TestController#getTest');
Add your controllers in your folders:
controllers\
---- folder1
---- folder2
Create your route not specifying the folder:
Route::get('/product/dashboard', 'MakeDashboardController#showDashboard');
Run
composer dump-autoload
And try again
For those using Laravel 5 you need to set the namespace for the controller within the sub-directory (Laravel 5 is still in development and changes are happening daily)
To get a folder structure like:
Http
----Controllers
----Admin
PostsController.php
PostsController.php
namespace Admin\PostsController.php file like so:
<?php namespace App\Http\Controller\Admin;
use App\Http\Controllers\Controller;
class PostsController extends Controller {
//business logic here
}
Then your route for this is:
$router->get('/', 'Admin\PostsController#index');
And lastly, don't for get to do either composer or artisan dump
composer dump-autoload
or
php artisan dump
For ** Laravel 5 or Laravel 5.1 LTS both **, if you have multiple Controllers in Admin folder, Route::group will be really helpful for you. For example:
Update: Works with Laravel 5.4
My folder Structure:
Http
----Controllers
----Api
----V1
PostsApiController.php
CommentsApiController.php
PostsController.php
PostAPIController:
<?php namespace App\Http\Controllers\Api\V1;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
class PostApiController extends Controller {
...
In My Route.php, I set namespace group to Api\V1 and overall it looks like:
Route::group(
[
'namespace' => 'Api\V1',
'prefix' => 'v1',
], function(){
Route::get('posts', ['uses'=>'PostsApiController#index']);
Route::get('posts/{id}', ['uses'=>'PostssAPIController#show']);
});
For move details to create sub-folder visit this link.
1.create your subfolder just like followings:
app
----controllers
--------admin
--------home
2.configure your code in app/routes.php
<?php
// index
Route::get('/', 'Home\HomeController#index');
// admin/test
Route::group(
array('prefix' => 'admin'),
function() {
Route::get('test', 'Admin\IndexController#index');
}
);
?>
3.write sth in app/controllers/admin/IndexController.php, eg:
<?php
namespace Admin;
class IndexController extends \BaseController {
public function index()
{
return "admin.home";
}
}
?>
4.access your site,eg:localhost/admin/test
you'll see "admin.home" on the page
ps: Please ignore my poor English
In Laravel 5.6, assuming the name of your subfolder' is Api:
In your controller, you need these two lines:
namespace App\Http\Controllers\Api;
use App\Http\Controllers\Controller;
And in your route file api.php, you need:
Route::resource('/myapi', 'Api\MyController');
Just found a way how to do it:
Just add the paths to the /app/start/global.php
ClassLoader::addDirectories(array(
app_path().'/commands',
app_path().'/controllers',
app_path().'/controllers/product',
app_path().'/models',
app_path().'/database/seeds',
));
php artisan make:controller admin/CategoryController
Here
admin is sub directory under app/Http/Controllers and
CategoryController is controller you want to create inside directory
I am using Laravel 4.2. Here how I do it:
I have a directory structure like this one:
app
--controllers
----admin
------AdminController.php
After I have created the controller I've put in the composer.json the path to the new admin directory:
"autoload": {
"classmap": [
"app/commands",
"app/controllers",
"app/controllers/admin",
"app/models",
"app/database/migrations",
"app/database/seeds",
"app/tests/TestCase.php"
]
},
Next I have run
composer dump-autoload
and then
php artisan dump-autoload
Then in the routes.php I have the controller included like this:
Route::controller('admin', 'AdminController');
And everything works fine.
If you're using Laravel 5.3 or above, there's no need to get into so much of complexity like other answers have said.
Just use default artisan command to generate a new controller.
For eg, if I want to create a User controller in User folder.
I would type
php artisan make:controller User/User
In routes,
Route::get('/dashboard', 'User\User#dashboard');
doing just this would be fine and now on localhost/dashboard is where the page resides.
Hope this helps.
1) That is how you can make your app organized:
Every route file (web.php, api.php ...) is declared in a map() method, in a file
\app\Providers\RouteServiceProvider.php
When you mapping a route file you can set a ->namespace($this->namespace) for it, you will see it there among examples.
It means that you can create more files to make your project more structured!
And set different namespaces for each of them.
But I prefer set empty string for the namespace ""
2) You can set your controllers to rout in a native php way, see the example:
Route::resource('/users', UserController::class);
Route::get('/agents', [AgentController::class, 'list'])->name('agents.list');
Now you can double click your controller names in your IDE to get there quickly and conveniently.
I think to keep controllers for Admin and Front in separate folders, the namespace will work well.
Please look on the below Laravel directory structure, that works fine for me.
app
--Http
----Controllers
------Admin
--------DashboardController.php
------Front
--------HomeController.php
The routes in "routes/web.php" file would be as below
/* All the Front-end controllers routes will work under Front namespace */
Route::group(['namespace' => 'Front'], function () {
Route::get('/home', 'HomeController#index');
});
And for Admin section, it will look like
/* All the admin routes will go under Admin namespace */
/* All the admin routes will required authentication,
so an middleware auth also applied in admin namespace */
Route::group(['namespace' => 'Admin'], function () {
Route::group(['middleware' => ['auth']], function() {
Route::get('/', ['as' => 'home', 'uses' => 'DashboardController#index']);
});
});
Hope this helps!!
This is for laravel 9.
Organize your controllers in subfolder as you wish:
controller
---folder-1
------controllerA
------controllerB
---folder-2
------controllerC
------controllerD
use the controllers in the route file
use App\Http\controllers\folder-1\controllerA;
.....etc
Write your routes as normal
Route::get('/xyz', [controllerA::class, 'methodName']);
I had this problem recently with laravel 5.8 but i underestand I should define controller in a right way like this below:
php artisan make:controller SubFolder\MyController // true
Not like this:
php artisan make:controller SubFolder/MyController // false
Then you can access the controller in routes/web.php like this:
Route::get('/my', 'SubFolder\MyController#index');
In my case I had a prefix that had to be added for each route in the group, otherwise response would be that the UserController class was not found.
Route::prefix('/user')->group(function() {
Route::post('/login', [UserController::class, 'login'])->prefix('/user');
Route::post('/register', [UserController::class, 'register'])->prefix('/user');
});
Create controller go to cmd and the type
php artisan make:controller auth\LoginController

Resources