Laravel namespacing routes - php

I have controllers in different folder than Laravel native App\Http\Controllers. I am using a custom Lib\MyApp folder which has modules inside. Each module has its own controllers, models etc. I added to composer.json autoloading to app\lib.
What I did is change RouteServiceProvider namespace:
protected $namespace = 'App\Lib\MyApp';
I did a composer dump-autoload after everything.
Inside MyApp is a Landing\Controller folder with actual controller class inside.
Try 1 (ideal):
I would like to call my route like this:
Route::get('/', 'Landing\Controller\LandingController#index');
But this way I am getting a ReflectionException that the class is not found even though
Try 2:
Route::get('/', '\Landing\Controller\LandingController#index');
Trailing slash gets rid of the namespace part when I refresh the page, and class is still said not to exist.
Try 3:
Route::get('/', 'MyApp\Landing\Controller\LandingController#index');
This just duplicates MyApp folder, and class is not found as expected.
Try 4 (working, but don't want it like that)
Route::get('/', '\MyApp\Landing\Controller\LandingController#index');
This works fine, although I would like to get rid of the \MyApp\ part.
Is something like this possible?

You can use the namespace in the routes for that purpose :
Route::namespace('Landing\Controller')->group(function () {
Route::get('/', 'LandingController#index');
// + other routes in the same namespace
});
And dont forget to add the namespace to the controllers :
<?php namespace App\Lib\MyApp\Landing\Controller;
PS : in the case where the Lib is inside the App folder there is no need to add a thing in the composer file, because the App folder is registred in the psr-4 and with this it will load all the files within this namespase for you.

There are many ways to add the namespace in Laravel
Route::group(['prefix' => 'prefix','namespace'=>'Admin'], function () {
// your routes with"App\Http\Controllers\Admin" Namespace
});
Route::namespace('Admin')->group(function () {
// your routes with"App\Http\Controllers\Admin" Namespace
});
//single route
Route::namespace('Admin')->get('/todo', 'TaskController#index');
//single route
Route::get('/todo', 'Admin/TaskController#index');
// by ->namespace
Route::prefix('admin')->namespace('Admin')->group(function () {
// route code
});

For "laravel 8"
Here I have given an example with both namespace and prefix but you can also use any one according to your requirement.
I created Controller in Controllers dir with command
php artisan make:controller Admin/StoriesController
Route::namespace('Admin')->prefix('admin')->group(function(){
Route::get('/deleted_stories',
'\App\Http\Controllers\Admin\StoriesController#index')->name
('admin.stories.index');
});

Related

Controllers not working on Laravel 8 despite uncommenting in RouteServiceProvider

I try to create routes to my index.blade.php page, i've made a controller "ProductController" using cmd php artisan make:controller ProductController, so in http --> Controllers i do have a ProductController.php file and i put this code in it :
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class ProductContoller extends Controller
{
public function index()
{
return view('products.index');
}
}
and then in my web.php i create a route using this code
Route::get('/boutique', 'ProductController#index');
However it doesn't work.
Firstly, when i go to the pretty url i've setup for my project at localhost using Laragon --> Projetname.test i get the normal Laravel Welcome page, but when i try to go to the url i've just setup like : ProjectName.test/boutique, i get
"Target class [App\Http\Controllers\ProductController] does not exist."
After reading about the changes since the update of Laravel to V8 here, i've seen that the update made some requirements for routes since $namespace prefix are not enabled automatically, but however that can be enabled again by uncommenting this line in RouteServiceProvider
// protected $namespace = 'App\\Http\\Controllers';
I do uncommenting that line and then clear the cache using php artisan route:cache, however it still not working..
When i first started doing research about routes issues in Laravel i've seen many forum spotted out that apache Allowoverride settings in httpd.config file may cause issue, so i change it settings from None to All and then restart Laragon but nothing works.
After correcting label on my controller it still do not work, i try both methode (the old and the new one) none of them works for me, cmd keeps returning me :
λ php artisan route:list
Illuminate\Contracts\Container\BindingResolutionException
Target class [ProductController] does not exist.
at C:\laragon\www\ProjectName\vendor\laravel\framework\src\Illuminate\Container\Container.php:835
831▕
832▕ try {
833▕ $reflector = new ReflectionClass($concrete);
834▕ } catch (ReflectionException $e) {
➜ 835▕ throw new BindingResolutionException("Target class [$concrete] does not exist.", 0, $e);
836▕ }
837▕
838▕ // If the type is not instantiable, the developer is attempting to resolve
839▕ // an abstract type such as an Interface or Abstract Class and there is
1 [internal]:0
Illuminate\Foundation\Console\RouteListCommand::Illuminate\Foundation\Console\{closure}(Object(Illuminate\Routing\Route))
2 C:\laragon\www\ProjectName\vendor\laravel\framework\src\Illuminate\Container\Container.php:833
ReflectionException::("Class "ProductController" does not exist")
Laravel 8 Route should be
Route::get('/boutique', [NameController:class,'method']);
So in your web.php file add
use App\Http\Controllers\ProductContoller
Then write your route like this:
Route::get('/boutique', [ProductContoller::class,'index']);
And I think there is a missing 'r' in your "ProductController" class name
I found out after watching a tutorial here on most common issues with new routing methodes on Laravel 8 that when uncommenting the RouteServiceProvider, using the old method require to use the old route method too on web.php, so it looks like that :
Route::get('/boutique', 'ProductController#index');
Please use
Route::get('/boutique', '\App\Http\Controllers\ProductController#index');
or use name route group and indicate the namespace
Route::group(['namespace' => 'App\Http\Controllers'], function(){
Route::get('/boutique', 'ProductController#index');
});
let me know how it works.

Method App\Http\Controllers\LanguagesController::index does not exist

LARAVEL
when I make a controller insid folder called "Admin" by command
"php artisan make:controller Admin\ControllerLanguages"
and Route the page This error appears:
Method App\Http\Controllers\LanguagesController::index does not exist.
Bad Method Call Did you mean
App\Http\Controllers\LanguagesController::validate() ?
but when i make the controller normally in the default folder by command:
"php artisan make:controller LanguagesController"
the route runs and the page appears, i want the page appears when i create it in "Admin" Folder, I tried many ways, but to no avail.
You should declare the namespace for the route group
Route::prefix('languages')
->namespace('App\Http\Controllers\Admin')
->group(function() {
Route::get('/', 'LanguagesController#index')->name('admin.languages');
//All other Routes for languages defined here
//LanguagesController is at app/Http/Controllers/Admin folder
});
Or you can import the namespace via use statement like, at the top
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\Admin\LanguagesController;
Route::prefix('languages')
->group(function(){
Route::get('/', [LanguagesController::class, 'index'])->name('admin.languages');
//Other languages routes here
});

Laravel Target class [App\Http\Controllers\App\Http\Controllers\ApiController] does not exist

For some reason, which is probably my fault, Laravel thinks it should be looking for the class ApiController in path: 'App\Http\Controllers\App\Http\Controllers', so... it doubles, but I have no idea why.
It's a brand new Laravel 6 project, I've created the ApiController with the make:controller artisan command and added a function, like this:
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class ApiController extends Controller
{
public function base() {
return 'This is a test function';
}
}
Then I've added a route to the api routes like this:
use App\Http\Controllers\ApiController;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
Route::group(['prefix' => '/v1', 'as' => 'api'], function () {
Route::get('/base', ['uses' => ApiController::class . '#base'])->name('base');
});
As you can see, I've even 'imported' the controller, but it just can't find it.
That's it, no other files or changes to the project. Also tried clearing route cache and dump-autoload, but that did not change anything.
In my case problew was, in RouteServiceProvider, in using routes Namespace
protected $namespace = 'App\Http\Controllers';
In Laravel 8 namespace was commented out, i remove namespace from chain, because my web routes not fully moved to Laravel 8 syntax and i need this namespace.
Route::prefix('api')
->middleware('api')
-̶>̶n̶a̶m̶e̶s̶p̶a̶c̶e̶(̶$̶t̶h̶i̶s̶-̶>̶n̶a̶m̶e̶s̶p̶a̶c̶e̶)̶
->group(base_path('routes/admin-api.php'));
If you wanna ::class reference in the router, it should be done like this.
Route::group(['prefix' => '/v1', 'as' => 'api'], function () {
Route::get('base', [ApiController::class, 'base'])->name('base');
});
This should work:
Route::group(['prefix' => '/v1', 'as' => 'api'], function () {
Route::get('base', 'ApiController#base')->name('base');
});
No need to add the "use", since controllers are referenced from the App/Controllers namespace, as you can corroborate on the RouteServiceProvider.
The syntax of your route is a combination of "old syntax" vs "new syntax"
What you are trying to achieve is:
Route::get('/base', [ApiController::class, 'base'])->name('base');
Either remove this line:
use App\Http\Controllers\ApiController;
or add a \ to the start:
use \App\Http\Controllers\ApiController;
In my case (Laravel 8 project), I needed a separate route for destroy, because deleting didn't use html form, so my web.php file is like:
use App\Http\Controllers\LocationController;
...
Route::resource('/locations', LocationController::class);
Route::get('/locations/destroy/{location}', [LocationController::class, 'destroy']);
But in that case if I put use App\Http\Controllers\LocationController the first line (Route::resource...) fails, if I remove it then the second line fails. So I removed use line and added App\Http\Controllers into the second line:
Route::resource('/locations', LocationController::class);
Route::get('/locations/destroy/{location}', [App\Http\Controllers\LocationController::class, 'destroy']);
So obviously Laravel doesn't automatically add App\Http\Controllers in the second form of Route.
I got this error when in resource controller description me pasted one from fresh project:
Route::resources([
'my_url' => LisseyDoruHisobotController:class,
..., //other controllers
]);
as being a recommended signature in Laravel 8 , but am currently busy on 7 or 6 version, where should be:
Route::resources([
'my_url' => 'path\to\LisseyDoruHisobotController',
..., //other controllers
]);
otherwize it will show doubled path
Laravel Target class [App\Http\Controllers\App\Http\Controllers\ ] does not exist

Laravel: Not picking up __invoke method?

Trying to use invokable controllers, but it seems to fail to find the __invoke method?
Invalid route action: [App\Http\Controllers\App\Http\Controllers\MainController].
It seems to be returning true on:
if (! method_exists($action, '__invoke')) {
throw new UnexpectedValueException("Invalid route action: [{$action}].");
}
Routes:
<?php
Route::get('/', \App\Http\Controllers\MainController::class);
MainController:
<?php
namespace App\Http\Controllers;
class MainController extends Controller
{
public function __invoke()
{
dd('main');
}
}
Laravel by default assumes that your controllers will be located at App\Http\Controllers\. So when you're adding the full path to your controller, Laravel will check it there, at App\Http\Controllers\App\Http\Controllers\MainController.
To solve it simply remove the namespace when you're registering the route, and register it like this:
Route::get('/', MainController::class);
Alternatively, you can stop this behavior by removing ->namespace($this->namespace) from mapWebRoutes() method on RouteServiceProvider class, which is located at App\Providers folder. Then you can register your routes like this:
Route::get('/', \App\Http\Controllers\MainController::class);
Alternatively, you can use:
use App\Http\Controllers\MainController;
Route::get('/', [MainController::class, '__invoke']);
In this case, the namespace provided in RouteServiceProvider won't be taken into account.
The advantage of this is that now your IDE will be able to reference the class usage and you can navigate by clicking on it.
The best answer that works for everyone is laravel documentation.
just use this at the top of your route(web.php) if (websiteController is the name of your controller)
use App\Http\Controllers\WebsiteController;
and define your route like this for your index page
Route::get('/', [WebsiteController::class, 'index']);
take note of the
[ ]
You have to create the crontoller with argument "--invokable"
php artisan make:controller YourController --invokable
Always Declare/Use in Top
use App\Http\Controllers\backend\DashboardController;
Then Use this way
Route::get('/dashboard', [DashboardController::class, 'dashboard'])->name('dashboard');
If have Auth and Use Group
Route::middleware([
'auth:sanctum',
config('jetstream.auth_session'),
'verified'
])->group(function () {
Route::get('/dashboard', [DashboardController::class, 'dashboard'])->name('dashboard');
})
Change your route to:
Route::get('/', "MainController");
In my case I forget to set #action, so change your code from:
Route::get('admin/orders', 'Admin\OrderController')->name('admin.orders');
to:
Route::get('admin/orders', 'Admin\OrderController#index')->name('admin.orders');
you have mentioned get link, but you have not declared which method it should call.
Route::get('/', \App\Http\Controllers\MainController::class);// if you are importing lass like this you have to use resource instead of get.
you can solve this issue by two ways,
first way,
Route::get('/', '\App\Http\Controllers\MainController#index'); // you have to mention your method which you have mentioned in controller
another way is,
Route::resource('/', \App\Http\Controllers\MainController::class);
In, 2nd method laravel will automatically find which request and where should redirect.2nd option is prefered if you are using multiple method for the same route.
Route::resource('/', \App\Http\Controllers\MainController::class);
Use method 'resource'

ReflectionException Class App\Http\Controllers\StaticPagesController#faq does not exist Laravel-5

I cloned this todstoychev/Laravel5Starter from Github and installed it.
After creating this StaticPagesController controller and updating my routes.php file. The controller does not seem to work. For some reason i keep getting the following error.
ReflectionException in ControllerInspector.php line 32:
Class App\Http\Controllers\StaticPagesController#faq does not exist
My routes.php file
<?php
// Admin routes
Route::group(['prefix' => 'admin', 'namespace' => 'Admin'], function () {
Route::controller('permissions', 'AdminPermissionsController');
Route::controller('settings', 'AdminSettingsController');
Route::controller('roles', 'AdminRolesController');
Route::controller('users', 'AdminUsersController');
Route::controller('/', 'AdminController');
});
// Public and user routes
Route::controller('contacts', 'ContactsController');
Route::controller('users', 'UsersController');
Route::controller('/', 'IndexController');
Route::controller('faq', 'StaticPagesController#faq');
My StaticPagesController.php file
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
class StaticPagesController extends Controller
{
public function faq(){
return 'this is faq page';
}
}
I have tried composer update, php artisan acl:update, composer dumpautoload to no avail.
Please help me. Thanks
With this line:
Route::controller('faq', 'StaticPagesController#faq');
You are telling Laravel that the controller for faq shoule be StaticPagesController#faq. The Route::controller method sets an entire controller for a route, it does not specify a method to be used on that route, Laravel handles this internally. Take a look at your error to prove my point:
Class App\Http\Controllers\StaticPagesController#faq does not exist
It is looking for class StaticPagesController#faq not StaticPagesController as you are intending.
Unless you are building an API using REST, you should not use the controller method and instead specify your routes explicitly, i.e.
Route::get('faq', 'StaticPagesController#faq');
This will use the faq method on your controller when the user makes a GET request to the URI faq. If you insist on using the controller method, then remove the #faq from the second argument and you will be good, although I'm pretty sure Laravel expects the methods index, show, create, etc to be in your controller. I suggest taking a look at the Laravel 5 Fundamentals video course to help you get a better understanding.

Categories