Target class [] does not exist - Laravel 8 [duplicate] - laravel

Here is my controller:
<?php
namespace App\Http\Controllers\Api;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
class RegisterController extends Controller
{
public function register(Request $request)
{
dd('aa');
}
}
As seen in the screenshot, the class exists and is in the correct place:
My api.php route:
Route::get('register', 'Api\RegisterController#register');
When I hit my register route using Postman, it gave me the following error:
Target class [Api\RegisterController] does not exist.
How can I fix it?
Thanks to the answers, I was able to fix it. I decided to use the fully qualified class name for this route, but there are other options as described in the answers.
Route::get('register', 'App\Http\Controllers\Api\RegisterController#register');

You are using Laravel 8. In a fresh install of Laravel 8, there is no namespace prefix being applied to your route groups that your routes are loaded into.
"In previous releases of Laravel, the RouteServiceProvider contained a $namespace property. This property's value would automatically be prefixed onto controller route definitions and calls to the action helper / URL::action method. In Laravel 8.x, this property is null by default. This means that no automatic namespace prefixing will be done by Laravel." Laravel 8.x Docs - Release Notes
You would have to use the Fully Qualified Class Name for your Controllers when referring to them in your routes when not using the namespace prefixing.
use App\Http\Controllers\UserController;
Route::get('/users', [UserController::class, 'index']);
// or
Route::get('/users', 'App\Http\Controllers\UserController#index');
If you prefer the old way:
App\Providers\RouteServiceProvider:
public function boot()
{
...
Route::prefix('api')
->middleware('api')
->namespace('App\Http\Controllers') // <---------
->group(base_path('routes/api.php'));
...
}
Do this for any route groups you want a declared namespace for.
The $namespace property:
Though there is a mention of a $namespace property to be set on your RouteServiceProvider in the Release notes and commented in your RouteServiceProvider this does not have any effect on your routes. It is currently only for adding a namespace prefix for generating URLs to actions. So you can set this variable, but it by itself won't add these namespace prefixes, you would still have to make sure you would be using this variable when adding the namespace to the route groups.
This information is now in the Upgrade Guide
Laravel 8.x Docs - Upgrade Guide - Routing
With what the Upgrade Guide is showing the important part is that you are defining a namespace on your routes groups. Setting the $namespace variable by itself only helps in generating URLs to actions.
Again, and I can't stress this enough, the important part is setting the namespace for the route groups, which they just happen to be doing by referencing the member variable $namespace directly in the example.
Update:
If you have installed a fresh copy of Laravel 8 since version 8.0.2 of laravel/laravel you can uncomment the protected $namespace member variable in the RouteServiceProvider to go back to the old way, as the route groups are setup to use this member variable for the namespace for the groups.
// protected $namespace = 'App\\Http\\Controllers';
The only reason uncommenting that would add the namespace prefix to the Controllers assigned to the routes is because the route groups are setup to use this variable as the namespace:
...
->namespace($this->namespace)
...

Yes, in Laravel 8 this error does occur.
After trying many solutions I got this perfect solution.
Just follow the steps...
Case 1
We can change in api.php and in web.php files like below.
The current way we write syntax is
Route::get('login', 'LoginController#login');
That should be changed to:
Route::get('login', [LoginController::class, 'login']);
Case 2
First go to the file: app > Providers > RouteServiceProvider.php
In that file replace the line
protected $namespace = null; with protected $namespace = 'App\Http\Controllers';
Then add line ->namespace($this->namespace) as shown in image...

In Laravel 8 you just add your controller namespace in routes\web.php
use App\Http\Controllers\InvoiceController; // InvoiceController is controller name
Route::get('invoice',[InvoiceController::class, 'index']);
Or go to: app\Providers\RouteServiceProvider.php path and remove the comment:
protected $namespace = 'App\\Http\\Controllers';

In Laravel 8 the default is to remove the namespace prefix, so you can set the old way in Laravel 7 like:
In RouteServiceProvider.php, add this variable:
protected $namespace = 'App\Http\Controllers';
And update the boot method:
public function boot()
{
$this->configureRateLimiting();
$this->routes(function () {
Route::middleware('web')
->namespace($this->namespace)
->group(base_path('routes/web.php'));
Route::prefix('api')
->middleware('api')
->namespace($this->namespace)
->group(base_path('routes/api.php'));
});
}

The way to define your routes in Laravel 8 is either
// Using PHP callable syntax...
use App\Http\Controllers\HomeController;
Route::get('/', [HomeController::class, 'index']);
Or
// Using string syntax...
Route::get('/', 'App\Http\Controllers\HomeController#index');
A resource route becomes
// Using PHP callable syntax...
use App\Http\Controllers\HomeController;
Route::resource('/', HomeController::class);
This means that in Laravel 8, there isn't any automatic controller declaration prefixing by default.
If you want to stick to the old way, then you need to add a namespace property in the
app\Providers\RouteServiceProvider.php and activate in the routes method.

Laravel 8 updated RouteServiceProvider and it affects routes with the string syntax. You can change it like in previous answers, but the recommended way is using action syntax, not using route with string syntax:
Route::get('register', 'Api\RegisterController#register');
It should be changed to:
Route::get('register', [RegisterController::class, 'register']);

I got the same error when I installed Laravel version 8.27.0:
The error is as follows:
But when I saw my app/Providers/RouteServiceProvider.php file, I had namespaces inside my boot method. Then I just uncommented this => protected $namespace = 'App\\Http\\Controllers';.
Now my project is working.

If you are using Laravel 8, just copy and paste my code:
use App\Http\Controllers\UserController;
Route::get('/user', [UserController::class, 'index']);

The Laravel 8 documentation actually answers this issue more succinctly and clearly than any of the answers here:
Routing Namespace Updates
In previous releases of Laravel, the RouteServiceProvider contained a $namespace property. This property's value would automatically be prefixed onto controller route definitions and calls to the action helper / URL::action method. In Laravel 8.x, this property is null by default. This means that no automatic namespace prefixing will be done by Laravel. Therefore, in new Laravel 8.x applications, controller route definitions should be defined using standard PHP callable syntax:
use App\Http\Controllers\UserController;
Route::get('/users', [UserController::class, 'index']);
Calls to the action related methods should use the same callable syntax:
action([UserController::class, 'index']);
return Redirect::action([UserController::class, 'index']);
If you prefer Laravel 7.x style controller route prefixing, you may simply add the $namespace property into your application's RouteServiceProvider.

Also check your route web.php file if your RegisterController is properly in place..
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\Auth\RegisterController;
Route::get('/register',[RegisterController::class,'index'])->name('register');
Route::post('/register',[RegisterController::class,'store']);
Route::get('/', function () {
return view('test.index');
});

For the solution, just uncomment line 29:
protected $namespace = 'App\\Http\\Controllers';
in the app\Providers\RouteServiceProvider.php file.
Just uncomment line 29

If you would like to continue using the original auto-prefixed controller routing, you can simply set the value of the $namespace property within your RouteServiceProvider and update the route registrations within the boot method to use the $namespace property:
class RouteServiceProvider extends ServiceProvider
{
/**
* This namespace is applied to your controller routes.
*
* In addition, it is set as the URL generator's root namespace.
*
* #var string
*/
protected $namespace = 'App\Http\Controllers';
/**
* Define your route model bindings, pattern filters, etc.
*
* #return void
*/
public function boot()
{
$this->configureRateLimiting();
$this->routes(function () {
Route::middleware('web')
->namespace($this->namespace)
->group(base_path('routes/web.php'));
Route::prefix('api')
->middleware('api')
->namespace($this->namespace)
->group(base_path('routes/api.php'));
});
}

Yes, check if your web.php in the routes folder has the Controller class used.
use App\Http\Controllers\<name of controlelr class>

Just uncomment the below line from RouteServiceProvider (if does not exists then add it):
protected $namespace = 'App\\Http\\Controllers';

One important thing to make sure you do after each change on the routes is clearing the cache (using Laravel 9):
php artisan route:clear

In my case, I had the same error, because I forgot to capitalize the first letter of controllers in the path.
So I changed
use App\Http\controllers\HomeController;
to this:
use App\Http\Controllers\HomeController;

In Laravel 8 you can use it like this:
Route::group(['namespace'=>'App\Http\Controllers', 'prefix'=>'admin',
'as'=>'admin.', 'middleware' => ['auth:sanctum', 'verified']], function()
{
Route::resource('/dashboard', 'DashboardController')->only([
'index'
]);
});

On a freshly installed Laravel 8, in the App/Providers/RouteServices.php file:
/*
* The path to the "home" route for your application.
*
* This is used by Laravel authentication to redirect users after login.
*
* #var string
*/
public const HOME = '/home';
/**
* The controller namespace for the application.
*
* When present, controller route declarations will automatically be prefixed with this namespace.
*
* #var string|null
*/
// protected $namespace = 'App\\Http\\Controllers';
Uncomment line
protected $namespace = 'App\\Http\\Controllers';
That should help you run Laravel the old-fashioned way.
In case you are upgrading from lower versions of Laravel to 8 then you might have to implicitly add line
protected $namespace = 'App\\Http\\Controllers';
in the RouteServices.php file for it to function the old way.

Ensure you're using the correct name of the file in your route.
For example:
If your controller file was named User.php, make that you're referencing it with User and not UserController.

In Laravel 9, there isn't any need to add a namespace in RouteServiceProvider.
Instead of
Route::resource('tickets', 'TicketController');
use
Route::resource('tickets', TicketController::class);

I tried everything, didn't work, until I tried this 2nd time
restart server
php artisan cache:clear
php artisan optimize
php artisan route:list

In case if you prefer grouping of these routes, you can do it as:
Route::group(['namespace' => 'App\Http\Controllers\Api'], function () {
Route::resource('user', 'UserController');
Route::resource('book', 'BookController');
});

I faced the same error when running php artisan route:list. In my case I had deleted the recourse controller yet the route was still defined. I had to make sure the class in question was commented off in my routes/web.php.

In Laravel 8 the way routes are specified has changed:
Route::resource('homes', HomeController::class)->names('home.index');

I had this error:
(Illuminate\Contracts\Container\BindingResolutionException
Target class [App\Http\Controllers\ControllerFileName] does not exist.
Solution:
Just check your class name. It should be the exact same of your file name.

It happened to me when I was passing null to the middleware function:
Route::middleware(null)->group(function () {
Route::get('/some-path', [SomeController::class, 'search']);
});
Passing [] for no middleware works. Or probably just remove the middleware call if not using middleware :D

In the app/Providers folder, file RouteServiceProvider.php, change the protected $namespace variable to
protected $namespace = 'App\\Http\\Controllers';
This will auto-comment the variable on save.

Related

Call to undefined method Laravel\Passport\Passport::routes()

I tried to use Laravel-passport so I installed this package in my project, but when i wanted to make route
i wrote this code in the AuthServiceProvider
public function boot()
{
$this->registerPolicies();
Passport::routes();
}
When i run php artisan route:list in the cmd i face with this error
Call to undefined method Laravel\Passport\Passport::routes()
Since version 11 passport's routes have been moved to a dedicated route file. You can remove the Passport::routes() call from your application's service provider.
If you dont want to use default passport routes. you can disabled the route in register method inside AppServicerProvider
public function register()
{
Passport::ignoreRoutes();
}
and you can copy the default passport routes from vendor laravel\passport\routes\web.php
for more detail about UPGRADE read this https://github.com/laravel/passport/blob/11.x/UPGRADE.md
Remove this comment on this line on your AuthServiceProvider file.
protected $policies = [
'App\Models\Model' => 'App\Policies\ModelPolicy',
];

Voyager and Jetstream: Login to Admin Panel leads to Dashboard Page

I just started my first Laravel project and try to combine Jetstream Authentification with Voyager Admin Panel.
First of all, I installed Jetstream on a fresh Laravel installation and it worked so far:
Afterwards, I tried to add Voyager to generate the CRUDs for my website and added a new user with
php artisan voyager:admin your#email.com --create
But whenever I tried to login through the url "../admin", I was redirected to "../dashboard" from Jetstream.
Even if I reentered "../admin" as URL, I was redirected. As long as I was logged in, I cannot enter the Voyager Backend.
So I guess it's some kind of routing / middleware issue, but I cannot find out which issue it is.
Within the web.php Routing file, there's only the basic stuff:
use Illuminate\Support\Facades\Route;
Route::get('/', function () {
return view('welcome');
});
Route::middleware(['auth:sanctum', 'verified'])->get('/dashboard', function () {
return view('dashboard');
})->name('dashboard');
Route::group(['prefix' => 'admin'], function () {
Voyager::routes();
});
Not sure if that's relevant, but my IDE recognizes Voyager:: as unknown class, even it works the same way on a different Laravel installation.
But from the look of it, I expected the Route::middleware() to redirect a logged in person which types the url "../dashboard" to the Dashboard view, but nothing more. Removing this Route also didnt help the problem, so I guess I was wrong.
But beside this, only the pure Voyager Routes are left, so I'm not sure where else I can look to solve this problem.
You can add custom responses on app/Http/Responses directory.
just make new responses called LoginResponse
then use this code
<?php
namespace App\Http\Responses;
use Laravel\Fortify\Contracts\LoginResponse as LoginResponseContract;
class LoginResponse implements LoginResponseContract
{
/**
* #param $request
* #return mixed
*/
public function toResponse($request)
{
$home = auth()->user()->is_admin ? '/admin' : '/dashboard';
return redirect()->intended($home);
}
}
Then, bind your LoginResponse in FortifyServiceProvider
You can use this code
<?php
namespace App\Providers;
// ...
use App\Http\Responses\LoginResponse;
use Laravel\Fortify\Contracts\LoginResponse as LoginResponseContract;
class FortifyServiceProvider extends ServiceProvider
{
/**
* Bootstrap any application services.
*
* #return void
*/
public function boot()
{
// ...
$this->app->singleton(LoginResponseContract::class, LoginResponse::class);
}
}
i know that it to late but for other users who had the same problem.
first i installed jetstream
int .env file APP_URL=http://localhost:8000
i installed voyager with dummy data
i added manualy in table user_roles this ligne ( the admin )
INSERT INTO `user_roles` (`user_id`, `role_id`) VALUES ('1', '1');
and it work
you can see this video i found in youtube i think it will help you .
https://www.youtube.com/watch?v=UDYZx5uIwmQ

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.

Target class [PostController] does not exist. but it dose

The error I am getting is: Target class [PostController] does not exist but it does.
Route web.php
Route::get('/post', 'PostController#index');
Route::post('/post', 'PostController#store');
Route::get('/', function () {
return view('create');
});
PostController.php
namespace App\Http\Controllers;
use App\Post;
use Redirect,Response;
use Illuminate\Http\Request;
class PostController extends Controller
{
public function index()
{
return view('create');
}
public function store(Request $request)
{
$data = json_encode($request);
Post::create($data);
return back()->withSuccess('Data successfully store in json format');
}
}
This error comes in Laravel new version because there is no namespace prefix being applied to your route groups that your routes are loaded into. In the old version of Laravel, the RouteServiceProvider contained a $namespace property which would automatically be prefixed onto the controller route.
To solve this, you either can go to RouteServiceProvider and uncomment the line:
protected $namespace = 'App\\Http\\Controllers';
Or you can use closure-based syntax:
use App\Http\Controllers\PageController;
Route::get('/page', [PageController::class, 'index']);
Another way would be to use the fully qualified class names for your Controllers:
Route::get('/page', 'App\Http\Controllers\PageController#index');
use this line on the top of the (web.php) maybe your problem will resolve
use App\Http\Controllers\PostController;

Laravel 6.0 php artisan route:list returns “Target class [App\Http\Controllers\SessionsController] does not exist.”

I am using Laravel 6.0 and I try to list all my routes with artisan route:list, but it fails and returns:
Illuminate\Contracts\Container\BindingResolutionException : Target
class [App\Http\Controllers\SessionsController] does not exist.
at /home/vagrant/code/vendor/laravel/framework/src/Illuminate/Container/Container.php:806
802|
803| try {
804| $reflector = new ReflectionClass($concrete);
805| } catch (ReflectionException $e) {
> 806| throw new BindingResolutionException("Target class [$concrete] does not exist.", 0, $e);
807| }
808|
809| // If the type is not instantiable, the developer is attempting to resolve
810| // 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\SessionsController does not exist")
/home/vagrant/code/vendor/laravel/framework/src/Illuminate/Container/Container.php:804
3 ReflectionClass::__construct("App\Http\Controllers\SessionsController")
/home/vagrant/code/vendor/laravel/framework/src/Illuminate/Container/Container.php:804
Up to now I just have a very simple web.php routes file:
Route::get('/', function () {
return view('index');
});
Route::prefix('app')->group(function () {
// Registration routes
Route::get('registration/create', 'RegistrationController#create')->name('app-registration-form');
});
// Templates
Route::get('templates/ubold/{any}', 'UboldController#index');
Any idea how I could debug this issue?
I was upgrading from Laravel 7 to Laravel 8 (Laravel 8 is still a few days in development) and also had this issue.
The solution was to use a classname representation of the controller in the route:
So in web.php instead of
Route::get('registration/create', 'RegistrationController#create')
it is now:
Solution 1: Classname representation
use App\Http\Controllers\RegistrationController;
Route::get('/', [RegistrationController::class, 'create']);
Solution 2: String syntax
or as a string syntax (full namespaces controller name):
Route::get('/', 'App\Http\Controllers\RegistrationController#create');
Solution 3: Return to previous behaviour
As this should issue should only happen if you upgrade your application by creating a brand new laravel project you can also just add the default namespace to the RouteServiceProvider:
app/Providers/RouteServiceProvider.php
class RouteServiceProvider extends ServiceProvider
{
/* ... */
/** ADD THIS PROPERTY
* If specified, this namespace is automatically applied to your controller routes.
*
* In addition, it is set as the URL generator's root namespace.
*
* #var string
*/
protected $namespace = 'App\Http\Controllers';
/**
* Define your route model bindings, pattern filters, etc.
*
* #return void
*/
public function boot()
{
$this->configureRateLimiting();
$this->routes(function () {
Route::middleware('web')
->namespace($this->namespace) // <-- ADD THIS
->group(base_path('routes/web.php'));
Route::prefix('api')
->middleware('api')
->namespace($this->namespace) // <-- ADD THIS
->group(base_path('routes/api.php'));
});
}
/* ... /*
}
See also https://laravel.com/docs/8.x/routing#basic-routing or https://laravel.com/docs/8.x/upgrade (search for "Routing").
For those who have similar issue with Illuminate\Contracts\Container\BindingResolutionException : Target class [<className>] does not exist. message, this also could be helpful:
composer dump-autoload
Run this command
php artisan config:cache
In my case it was solved by running
php artisan optimize:clear
php artisan config:cache
The optimize:clearcommands clears everything
In my case it was a matter of Linux's file name case sensitivity. For a file named IndexController, having Indexcontroller will work in windows but not in Linux
Simply add the following line in app->Providers->RouteServiceProvider.php
protected $namespace = 'App\\Http\\Controllers';
In my case same error occurred because of forward slash / but it should be backward slash \ in defining route,
it happens when you have controller in folder like as in my case controller was in api Folder, so always use backward slash \ while mentioning controller name.
see example:
Error-prone code:
Route::apiResource('categories', 'api/CategoryController');
Solution code:
Route::apiResource('categories', 'api\CategoryController');
This is the perfect answer, I think:
Option 1:
use App\Http\Controllers\HomepageController;
Route::get('/', [HomepageController::class, 'index']);
Option 2:
Route::get('/', 'App\Http\Controllers\HomepageController#index');
Alright i got similar problem, i was trying to be smart so i wrote this in my web.php
Route::group([
'middleware' => '', // Removing this made everything work
'as' => 'admin.',
'prefix' => 'admin',
'namespace' => 'Admin',
],function(){
});
All i had to do is just to remove all the unnecessary/unused option from group. That's all.
try to correct your controller name
my route was
Route::get('/lien/{id}','liensControler#show');
and my controller was
class liensController extends Controller
{
// all the methods of controller goes here.
}
I did all these
1: php artisan config:cache
2: checked for controller name spellings.
3: composer dump-autoload
4: Just changed the forward / slash to backward \ in route.
4th one worked for me.
Now You Can use controller outside controller folder
use App\Http\submit;
Route::get('/', [submit::class, 'index']);
Now my controller excited in http folder
You have to change in controller file something
<?php
namespace App\Http;
use Illuminate\Http\Request;
use Illuminate\Http\Controllers\Controller;
class submit extends Controller {
public function index(Request $req) {
return $req;
}
}
You can define a route to this controller action like so:
use App\Http\Controllers\UserController;
Route::get('user/{id}', [UserController::class, 'show']);
I am running Laravel 8.x on my pc.
This error gave me headache. To recreate the error, this is what I did:
First I created a controller called MyModelController.php
Secondly, I wrote a simple function to return a blade file containing 'Hello World', called myFunction.
Lastly, I created a Route:
Route::get('/','MyModelController#myFunction');
This did not work.
This was how I solved it.
First you would have to read the documentation on:
(https://laravel.com/docs/8.x/releases#laravel-8)
At the 'web.php' file this was the Route i wrote to make it work:
use App\Http\Controllers\MyModelController;
Route::get('/', [MyModelController::class, 'myFunction']);
on Larave 7 I had the same issue.
I checked the spelling of the controller name.
I recognize I have the wrong spelling in the "AlbumContoller" and I rename it to "AlbumController". so I forgot "r"
after I renamed the file and controller name and controller name in the web.php
Route::resource('albums', 'AlbumsController');
everything worked well
So You Don't need these two:
1- use App\Http\Controllers\IndexContoller;
2- Route::get('/', [MyModelController::class, 'myFunction']);
you have to specify full path to the class
Previously it was
Route::get('/wel','Welcome#index');
Now it has changed to
use App\Http\Controllers\Welcome;
Route::get('wel',[Welcome::class,'index']);
I had this problem while leaving an empty middleware class in my middleware groups by mistake :
/**
* The application's route middleware groups.
*
* #var array
*/
protected $middlewareGroups = [
'web' => [
Middleware\EncryptCookies::class,
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
\Illuminate\Session\Middleware\StartSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
Middleware\VerifyCsrfToken::class,
\Illuminate\Routing\Middleware\SubstituteBindings::class,
],
'api' => [
'throttle:100,1',
'bindings',
'localization',
'' // Was empty by mistake
],
];
replace-
Route::resource('/admin/UserOff','admin/UsersController');
with-
Route::resource('/admin/UserOff','admin\UsersController');
forward / with \
I had the same problem but with a middleware controller. So finally I linked that middleware in kerner.php file. It is located at app\Http\Kernel.php
I have added this line in route middleware.
'authpostmanweb' => \App\Http\Middleware\AuthPostmanWeb::class
protected $routeMiddleware = [
'auth' => \App\Http\Middleware\Authenticate::class,
'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
'cache.headers' => \Illuminate\Http\Middleware\SetCacheHeaders::class,
'can' => \Illuminate\Auth\Middleware\Authorize::class,
'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
'password.confirm' => \Illuminate\Auth\Middleware\RequirePassword::class,
'signed' => \Illuminate\Routing\Middleware\ValidateSignature::class,
'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
'verified' => \Illuminate\Auth\Middleware\EnsureEmailIsVerified::class,
'authpostmanweb' => \App\Http\Middleware\AuthPostmanWeb::class
];
just check web.php and see lower and upper case letters
On top of ensuring that you use the updated route syntax:
Route::get('/', [RegistrationController::class, 'create']);
make sure that at the top of your routes/web.php the controller is included in the name space like:
use App\Http\Controllers\RegistrationController;

Resources