Reputation: 1183
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
{
...
}
Upvotes: 0
Views: 973
Reputation: 4271
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'));
});
}
Upvotes: 0
Reputation: 725
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.
Upvotes: 1
Reputation: 2464
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.
Upvotes: 2