PHP Laravel - Controller does not exist - php

I am new to PHP and Laravel. I am creating my first Laravel API where I am working with Post object.
In order to do so I use a PostController. I have created this controller using the php artisan command: php artisan make:controller PostController --api. This created a PostController class inside the app\Http\Controllers.
When I want to append this controller to the api routes using the Route::resource function I came across something strange. The course I followed told me to declare the controller like so: Route::resource('posts', 'PostController');. When testing the api php artisan route:list this gave the following error:Target class [PostController] does not exist.
Then I did some research and found an other way to declare the controller inside the api routes using:
use App\Http\Controllers\PostController;
Route::resource('posts', PostController::class);
This worked for me but I don't have any clue why the first declaration failed. I have looked inside my PostController class to see any typo's. But I couldn't find any:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class PostController extends Controller
{
...
}

The reason for this is just like the exception says: it could not find the PostController in your declared namespace.
The reason for that highly depends on the Laravel version you are using. Laravel 8 removed the default namespacing to App\Http\Controllers, so if you are using Laravel 8 but have followed a tutorial for an earlier Laravel version, that might be the reason.
However, using the declaration using class imports is the better way to do it anyways, so I would stick with that.

Since Laravel 8, there were some changes to the automatic controller namespace prefixing.
https://laravel.com/docs/8.x/upgrade#routing
You can continue to use the original auto-prefixed controller routing, see the 4th paragraph on the upgrade documentation. But the new way is recommended.

You should tell Route::resource method the controller's namespace. As you did in your second try.
If you wanna do it with your first attempt, you can tell it the required namespace
Route::resource('posts', 'App\Http\Controllers\PostController');
You can also set the namespace in your App\Providers\RouteServiceProvider:
public function boot()
{
$this->routes(function () {
Route::prefix('api')
->middleware('api')
->namespace('App\Http\Controllers\Api')
->group(base_path('routes/api.php'));
});
}

Related

I am getting Target class [Uploadcontroller] does not exist in laravel 9 and I don't know how to solve this

web.php
use App\Http\Controllers\Uploadcontroller;
Route::post('/upload', [Uploadcontroller::class, 'upload']);
Uploadcontroller.php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class Uploadcontroller extends Controller
{
public function upload(Request $request){
dd($request->file('image'));
}
}
These are my route and controller codes. So, when I hit upload it is showing Uploadcontroller does not exist.I am new to Laravel and I don't know what is wrong here.
use the command
php artisan route:clear
and the web.php file
add in top
use App\Http\Controllers\UploadController;
Note:
Check that the letters of the file name and class name are the same case
Your codes seems just fine.
But dont forget everytime you add a Route to the 'web.php' file you need to rebuild the routing in Laravel.
Try run this in CMD:
php artisan optimize

Class Controller not found in laravel 4

I'm beginner in Laravel and when I'm trying to use Controller I'm getting this error
Illuminate\Contracts\Container\BindingResolutionException
Target class [PostsController] does not exist.
http://127.0.0.1:8000/posts
routes directory contain web.php to route and there I'm using
Route::get('/posts', 'PostsController#index');
to redirect to the class PostsController
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class PostsController extends Controller
{
public function index() {
echo "asdas";
}
}
Before diving into your problem, you should really not use Laravel 4. We are almost at version 9.
Laravel 4 lacks features, security fixes and current PHP versions support (yes, at the time of this writing, all versions < 7 shouldn't be used).
That being said, you probably have a good reason, like working on a legacy project that's hard to update.
What you could do is to use the fully qualified namespace inside your route file.
Route::get('/posts', '\App\Http\Controllers\PostsController#index');
Also, triple check that you are using Laravel 4. The problem you have could also be caused by one of the latest Laravel update (version 8) where the default namespace was removed from the App\Providers\RouteServiceProvider file.
If you made a mistake and you are on Laravel 8, then just use the following notation:
Route::get('/posts', [\App\Http\Controllers\PostsController::class,'index']);
[EDIT]
As mentioned in the comments, you could also uncomment // protected $namespace = 'App\\Http\\Controllers'; in your route file. Of course, this apply to Laravel 8 so if you are on Laravel 4, just ignore this edit.

Laravel not recognizing Controller __invoke()

Can't debug this simple routing issue, despite going through several similar posts.
TestController is not invokable. The controller class TestController
is not invokable. Did you forget to add the __invoke method or is the
controller's method missing in your routes file?
I have played around with it as many permutations as I can find on Stack and nothing changes it. I have confirmed that simple routing, ie:
Route::get('/', function () {
return view('welcome');
});
works, but I can't get the controllers to work. I have cleared the cache and uncommented the $namespace, nothing makes a difference. In fact, the error message doesn't seem to change, which leads me to believe it's not the routing but something to do with the Controllers. But I am a newb and am not seeing it.
from web.php:
Route::get('/test', TestController::class);
TestController.php:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class TestController extends Controller {
public function __invoke() {
return view('welcome');
}
}
This normally happens when you do not have the use statement for the FQCN of the controller.
In the routes file where you are declaring the route ensure that the use statement for the Controller namespace is added. Especially since Laravel 8.x the default namespace for controllers is not set to App\Http\Controllers unlike the earlier versions.
//routes file
use App\Http\Controllers\TestController;
Route::get('/test', TestController::class);
Just as a side note if you are using an invokable controller class to return just a view, you can use the Route::view() method instead
//Assuming that you have a resources/views/test.blade.php
Route::view('/test', 'test');
Maybe this helps someone similar to me, who overlooks a simple problem:
I wrote:
Route::post('controller/{resource}/action', \App\Http\Controllers\MyController::class, 'action')->name('controller.action');
Instead what I needed was:
Route::post('controller/{resource}/action', [\App\Http\Controllers\MyController::class, 'action'])->name('controller.action');
So basically I was missing the [] around the controller class and action params, they go together in an array - got to remember that. :)
Sorry if it is a just a tiny bit off-topic, but I searched for my problem and ended up here, therefore this just might help someone else too.
I don't know if you still need to hear this but change your
Route::get('/test', TestController::class);
into
Route::get('/test', [TestController::class, #MethodName]);
Also, call your model into the Controller.file
use App\Models\Test;

how laravel autoload classes and use them without initiate it?

I am trying to deep dive laravel concept. In the very first step i got stuck. Loading different classes and use them.
In the laravel routing (where you can register web routes for your application), there is no any use keyword used for using class and initiate Route class in web.php
Route::get('/home', 'HomeController#index')->name('home');
how Route::get run without using any class?
And when we go more deep using model class
namespace hosam\Http\Controllers\Auth;
use hosam\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Auth;
use Illuminate\Support\Facades\DB;
and we use Auth in aur code like this.
Auth::login($user);
from using use keyword does php load auth class in our code where we are using Use Auth?
All the route files under routes folder are loaded automatically by laravel. routes/web.php and laravel/api.php are assigned to middleware web and api respectively.
All the classes and namespaces in laravel are loaded from the composer autoloader.
These files are mapped in the RouteServiceProvider class under Provider folder. So that class use Route facade. As the web.php and api.php is not called directly so there is no need to initiate the class in the particiular file
//RouteServiceProvider.php
Route::middleware('web')
->namespace($this->namespace)
->group(base_path('routes/web.php'));
Routing
You can also make your Helper folder with HelperClass and run can be run from any where
make folder in app > Helpers folder.
make helper class Helpers.php
where you can write all your function like
function write_yourfunction(){
// your code
// return something
}
to load every where you can use service provider. Edit app > Providers > AppServiceProvider.php
public function register()
{
foreach (glob(app_path() . '/Helpers/*.php') as $filename) {
require_once($filename);
}
}
Now you can call write_yourfunction() from everywhere

Can't use $request in controller.index() with lumen / laravel (index should be compatible with App\Http\Controllers\Controller::index )

Using lumen 5.2, I am setting up a GET action that can have resource queries:
GET /expedientes?param1=value1&..paramn=valuen
In my routing I have:
$app->get('expedientes', 'ExpedientesController#index');
In my controller:
class ExpedientesController extends Controller
public function index(Request $request){
if ($request->has('name')) {
return $request->input('name');
}
}
}
The error I obtain:
Declaration of App\Http\Controllers\ExpedientesController::index(Illuminate\Http\Request $request) should be compatible with App\Http\Controllers\Controller::index
The funny thing is, if I rename the controler to a name different from "index", like "indexa" (in both the controller and the routing file) everything works perfectly.
So my question is: Using the standard function name "index" for getting a list of resources, which is the proper way to access the request?
Thanks a lot, regards,
Possible solution #1:
I found out that lumen doesn't use the same controllers as laravel ( lumen: App\Http\Controllers\Controller class not found with fresh install ).
Using
use Laravel\Lumen\Routing\Controller as BaseController;
In the controller so it inherits from lumen's controller
class ExpedientesController extends BaseController
allows me to use a Request parameter in the index method.
But I wonder. Is this the proper way? Even if it is, what would be the way to do this in laravel?

Categories