英文:
Target class [UserController] does not exist error in Laravel 10
问题
"Target class [UserController] does not exist" means "目标类 [UserController] 不存在" in Chinese.
英文:
I am a beginner and trying to save a small form in the database. Once I hit the submit button on the form, the error comes:
"Target class [UserController] does not exist"
I have already crawled online resources, got my code verified with chatgpt too. Everything seems to be ok.
My Code on route/web.php
<?php
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\UserController;
use App\Http\Controllers\Test;
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider and all of them will
| be assigned to the "web" middleware group. Make something great!
|
*/
Route::get('/', function () {
return view('welcome');
});
Route::post('/save-user', 'UserController@saveUser')->name('saveUser');
Route::get('/success', function () {
// return view('success');
return "ok";
})->name('success');
My Code on UserControll.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\User; // Import the User model
class UserController extends Controller
{
public function saveUser(Request $request)
{
// Validate the form data
$validatedData = $request->validate([
'username' => 'required',
'name' => 'required',
'phone' => 'required',
'email' => 'required|email',
'country' => 'required',
]);
// Create a new user instance with the validated data
$user = new User();
$user->username = $validatedData['username'];
$user->name = $validatedData['name'];
$user->phone = $validatedData['phone'];
$user->email = $validatedData['email'];
$user->country = $validatedData['country'];
// Save the user data
$user->save();
// Redirect the user to a success page or perform any desired actions
return redirect()->route('success');
}
}
Please help
答案1
得分: 2
你可以用以下代码替换原来的代码部分:
Route::post('/save-user', [UserController::class, 'saveUser'])->name('saveUser');
利用上面定义的导入方式。
英文:
You could replace:
Route::post('/save-user', 'UserController@saveUser')->name('saveUser');
With:
Route::post('/save-user', [UserController::class, 'saveUser'])->name('saveUser');
Making use of the import defined above.
答案2
得分: 2
从 Laravel 8+ 开始,他们更改了路由访问器。
尝试
Route::post('/save-user', [UserController::class, 'saveUser'])->name('saveUser');
阅读:路由模型绑定
英文:
From laravel 8+ they changed route accessor.
Try
Route::post('/save-user', [UserController::class, 'saveUser'])->name('saveUser');
>Read: Route Model Binding
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论