When create a new project with laravel 8 and I get this error.
Illuminate\Contracts\Container\BindingResolutionException Target class [SayhelloController] does not exist. http://127.0.0.1:8000/users/john
<?php
use Illuminate\Support\Facades\Route;
Route::get('/', function () {
return view('welcome');
});
Route::get('/users/{name?}' , [SayhelloController::class,'index']);
In laravel documents Routes controller class must define like this
// Using PHP callable syntax...
Route::get('/users', [UserController::class, 'index']);
// Using string syntax...
Route::get('/users', 'App\Http\Controllers\UserController@index');
Target class
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class SayhelloController extends Controller
{
public function index($name = null)
{
return 'Hello '.$name;
}
}
So I did exactly.
ref link https://laravel.com/docs/8.x/upgrade
use App\Http\Controllers\SayhelloController;
Route::get('/users/{name?}' , [SayhelloController::class,'index']);
or
Route::get('/users', 'App\Http\Controllers\UserController@index');
then in RouteServiceProvider.php
add this line
/**
* 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'; // need to add in Laravel 8
public function boot()
{
$this->configureRateLimiting();
$this->routes(function () {
Route::prefix('api')
->middleware('api')
->namespace($this->namespace) // need to add in Laravel 8
->group(base_path('routes/api.php'));
Route::middleware('web')
->namespace($this->namespace) // need to add in Laravel 8
->group(base_path('routes/web.php'));
});
}
Then you can use like
Route::get('/users/{name?}' , [SayhelloController::class,'index']);
Route::resource('/users' , SayhelloController::class);
or
Route::get('/users', 'UserController@index');