-2

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

lagbox
  • 48,571
  • 8
  • 72
  • 83

2 Answers2

2

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.

Sachin Bahukhandi
  • 2,378
  • 20
  • 29
2

From laravel 8+ they changed route accessor.

Try

Route::post('/save-user', [UserController::class, 'saveUser'])->name('saveUser');

Read: Route Model Binding

Abdulla Nilam
  • 36,589
  • 17
  • 64
  • 85