skip to Main Content

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 IlluminateSupportFacadesRoute;
use AppHttpControllersUserController;
use AppHttpControllersTest;

/*
|--------------------------------------------------------------------------
| 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 AppHttpControllers;

use IlluminateHttpRequest;
use AppModelsUser; // 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

2

Answers


  1. 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.

    Login or Signup to reply.
  2. From laravel 8+ they changed route accessor.

    Try

    Route::post('/save-user', [UserController::class, 'saveUser'])->name('saveUser');
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search