Target class [App\Http\Controllers\LoginController] does not exist - laravel

Laravel 6.x.
I'm creating custom multi-authentication Panels(Staff,Student,Admin) from Single Login Page.Error already mentioned in the title. also without using php artisan ui bootstrap --auth.
Web.php file.
Route::get('/index/sign-in', function () {
return view('log-in');
});
Route::get('/index/admin', function () {
return view('admin-dashboard');
});
Route::get('/index/student', function () {
return view('student-dashboard');
});
Route::get('/index/staff', function () {
return view('faculty-dashboard');
});
Route::middleware('auth')->group(function () {
Route::post('/index/dashboard/','LoginController#postlogin')->name('postlogin');
Route::post('/index/logout','LoginController#postlogout')->name('postlogout');
});
LoginController.php file
public function postlogout()
{
auth()->logout();
//session()->flash('message', 'Some goodbye message');
return redirect('/index/sign-in/');
}
public function postlogin()
{
$role=(Auth::user())->user_role;
if ($role=='admin'){
return 'index/admin';
}
elseif ($role=='staff'){
return 'index/staff';
}
elseif ($role=='student'){
return 'index/student';
}else
return 'index/sign-in';
}
}

If you didn't move the controller from his default location, is inside the Auth folder, in the controller folder (app/Http/Controllers/Auth)
So as your error Target class [App\Http\Controllers\LoginController] does not exist it's searching for the controller in the Controllers folders but not in the Auth subfolder, so The route is wrong.
Route::post('/index/logout','LoginController#postlogout')->name('postlogout');
should be
Route::post('/index/logout','Auth\LoginController#postlogout')->name('postlogout');
Best Regards.

I'm not sure if this is the default in Laravel 6, but the LoginController is likely under the Auth folder/namespace`:
app
- Http
-- Controllers
--- Auth
---- LoginController.php
...
In this case, you need to reference the namespace in your routes:
Route::middleware('auth')->group(function () {
Route::post('/index/dashboard/', 'Auth\LoginController#postlogin')->name('postlogin');
Route::post('/index/logout', 'Auth\LoginController#postlogout')->name('postlogout');
});

In your web.php file check all namespace passed, if their directory root is passed correctly or not.
in the upper part of web.php file you need to make sure of each controller root.
Such as you are using LoginController so you must pass use App\Http\Controllers\LoginController; or use App\Http\Controllers\Controller\LoginController;
according to your Http\Controller project structure

If you did not create the controller with the artisan command, delete it and create it with the php artisan create:controller LoginController command. This should get the problem resolved.

Can you check the namespace of the controller
namespace App\Http\Controllers\Auth;
class LoginController extends Controller

All the above solution didn't work for me, what did was using
php artisan route:clear

Related

Laravel edit route for basic CRUD application giving 404

I'm trying to set up a basic Laravel 9 CRUD application, and I cannot get the edit route working for the User Controller.
routes/web.php
Route::get('/dashboard', function () { return view('dashboard'); })
->middleware(['auth'])->name('dashboard');
use App\Http\Controllers\UserController;
Route::controller(UserController::class)->group(function(){
Route::get('user','index')->middleware('auth')->name('cases');
Route::get('user/create','create')->middleware('auth');
Route::post('user/create','store')->middleware('auth');
Route::get('user/{$id}/edit','edit')->middleware('auth');
Route::post('user/{$id}/edit','update')->middleware('auth');
Route::get('user/{$id}/delete','destroy')->middleware('auth');
Route::get('user/{id}','show')->middleware('auth');
});
require __DIR__.'/auth.php';
UserController.php
class UserController extends Controller
{
function edit(int $id)
{
echo 123;
}
I'm getting a 404 NOT FOUND page
Also, why don't I see the stack trace for this error?
Also, in some examples, I've seen people using the model class name as the parameter type in the controller method declaration, such as:
function edit(User $id)
{
echo 123;
}
However, I've also seen other examples using int instead. So which is the correct one?
First, inside your .env filte you should put
APP_ENV=local
APP_DEBUG=true
and change your web.php to:
<?php
use Illuminate\Support\Facades\Route;
Route::get('/dashboard', function () { return view('dashboard'); })->middleware(['auth'])->name('dashboard');
use App\Http\Controllers\UserController;
Route::controller(UserController::class)->group(function(){
Route::get('user','index')->middleware('auth')->name('cases');
Route::get('user/create','create')->middleware('auth');
Route::post('user/create','store')->middleware('auth');
Route::get('user/{id}/edit','edit')->middleware('auth');
Route::post('user/{id}/edit','update')->middleware('auth');
Route::get('user/{id}/delete','destroy')->middleware('auth');
Route::get('user/{id}','show')->middleware('auth');
});
require __DIR__.'/auth.php';
Then, try to run
php artisan route:list
and check if your routes are correct.
And try to remove middlewares inside user files, maybe you do not have login page and it redirects you there.
Be sure you are in the correct url like localhost/user/1/edit
Parameters in routes don't take a starting $. Change all occurrences of {$id} in your routes to just {id}:
Route::controller(UserController::class)->group(function(){
Route::get('user','index')->middleware('auth')->name('cases');
Route::get('user/create','create')->middleware('auth');
Route::post('user/create','store')->middleware('auth');
Route::get('user/{id}/edit','edit')->middleware('auth');
Route::post('user/{id}/edit','update')->middleware('auth');
Route::get('user/{id}/delete','destroy')->middleware('auth');
Route::get('user/{id}','show')->middleware('auth');
});
More on Route Parameters
Edit: you might also want to take a look at Resource Controllers. Something like Route::resource('users', UserController::class); will manage all of the required routes

Route group prefix not working in Laravel 8

I was trying to make a group routing with a prefix in Laravel 8. But when I tested it in http://localhost/mysite/admin/test/, it always throws error 404.
Here is the code in web.php:
Route::prefix('/admin', function() {
Route::get('/test', [Admin\LoginController::class, 'index']);
});
I created a controller in app/Http/Controller/Admin/ as the controller is inside Admin folder.
Here is the code in LoginController:
namespace App\Http\Controllers\Admin;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
class LoginController extends Controller
{
public function __construct()
{
//
}
public function index()
{
echo "Please login";
}
}
Can anybody show me what I am doing wrong to get it working?
You have to group the routes as stated in the documentation like:
Route::prefix('admin')->group(function () {
Route::get('/test', function () {
// Matches The "/admin/users" URL
});
});
In your case it would be:
use App\Http\Controllers\Admin\LoginController;
Route::prefix('admin')->group(function () {
Route::get('/test', [LoginController::class, 'index']);
});
I think it should be 'admin' not '/admin'.
That slash makes it:
http://localhost/mysite//admin/test
=>
http://localhost/admin/test
You can check all your routes using: php artisan route:list
Try this
use App\Http\Controllers\Admin\LoginController;
Route::prefix('admin')->group(function () {
Route::get('test', ['LoginController::class, index'])->name('test'); });

gives a 404 response when using /admin on the url

I have a problem when using /admin on the url, if I use it always gives a 404 response but, when I change /admin on web.php in other words like adnnin etc. there was no problem
here piece web.php
Route::middleware('isadmin')->group(function () {
Route::prefix('admin')->group(function () {
Route::get('/dashboard', [App\Http\Controllers\Admin\DashboardController::class, 'index']);
});
});
here my controller
namespace App\Http\Controllers\Admin;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
class DashboardController extends Controller
{
public function index () {
return view('pages.admin.dashboard');
}
}
Make sure you do not have a folder named admin in your public directory. The webserver will look for folder/files before falling back to handing the request off to the front loader public/index.php, the Laravel application.

Change InertiaJS-Laravel default RootView

I am using Laravel 8 and I have installed InertiaJS, but in my directory resources/views/ I have a single file called index.blade.php which I plan to use with InertiaJS.
By default, InertiaJS looks for a file inside that directory called app.blade.php. I know writing the following statement:
\Inertia\Inertia::setRootView('index');
Change the rootView and allow me to use the file I have created. It may seem like a stupid question, but as far as I see it, I can do 2 things ..
Rename file index.blade.php to app.blade.php
Write the previous sentence .. in one of the ServiceProviders that I have
I wonder the following:
InertiaJS-Laravel does not allow publishing a ServiceProvider with the command php artisan vendor:publish? (the output of this command does not show me anything to publish regarding this package)
To solve my problem I should create a ServiceProvider like: php artisan make:provider InertiaServiceProvider and then register it?
Or just add the previous statement to one of the ServiceProvider that already exist? Like in app/Http/Providers/RouteServiceProvider.php
What do you recommend that would be better?
I want to seek the largest possible organization in my project. Thank you very much in advance...
Update; after my initial answer (on 20-09-2020), Inertia introduced middleware to handle your Inertia requests.
As described in the answers below, you can use the command php artisan inertia:middleware to generate this middleware. You can set the root index with:
// Set root template via property
protected $rootView = 'app';
// OR
// Set root template via method
public function rootView(Request $request)
{
return 'app';
}
You can find more info in the docs.
Even tighter, just override the rootView method in App\Http\Middleware\HandleInertiaRequests like this...
public function rootView(Request $request)
{
if ($request->route()->getPrefix() == 'admin') {
return 'layout.admin';
}
return parent::rootView($request);
}
You can do this inside your controller on the fly.
<?php
namespace App\Http\Controllers;
use App\Models\User;
use Illuminate\Http\Request;
use Inertia\Inertia;
class NewsController extends Controller
{
public function index()
{
Inertia::setRootView('layouts.news');
$users = User::all();
return Inertia::render('News/Index', compact('users'));
}
}
Replace in the App\Http\Middleware\HandleInertiaRequests
protected $rootView = 'app';
with:
public function rootView(Request $request): string
{
if ($request->route()->getPrefix() === '/admin') {
return 'admin.app';
}
return 'app';
}
I think it would be easier to change it in App\Http\Middleware\HandleInertiaRequests.
Be sure to run php artisan inertia:middleware during inertia server-side installation.
Also include it in your web middleware group.
Then go to App\Http\Middleware\HandleInertiaRequests and change the $rootView property to the name of the blade file you want to use. Example:
protected $rootView = 'index';
Extended #Olu Udeh answer
overwrite handle method of App\Http\Middleware\HandleInertiaRequests middleware
public function handle(Request $request, Closure $next)
{
if($request->route()->getPrefix() == 'admin'){
$this->rootView = 'layouts.admin';
}
return parent::handle($request, $next);
}
In laravel 8 this work for me
App\Http\Middleware\HandleInertiaRequests
Code
public function rootView(Request $request)
{
if(request()->is('admin/*') or request()->is('admin'))
{
return 'admin';
}
return parent::rootView($request);
}

Laravel: Controller does not exist

I added new controller in /app/controllers/admin/ folder and added the route in /app/routes.php file as well. Then i run the following command to autoload them
php artisan dump-autoload
I got the following error
Mcrypt PHP extension required.
I followed instruction given at https://askubuntu.com/questions/460837/mcrypt-extension-is-missing-in-14-04-server-for-mysql and able to resolve the mcrypt issue.
After that i run the php artisan dump-autoload command but still getting following error
{"error":{"type":"ReflectionException","message":"Class CoursesController does not exist","file":"\/var\/www\/html\/vendor\/laravel\/framework\/src\/Illuminate\/Container\/Container.php","line":504}}
Here is code of my routes.php file
Route::group(array('before' => 'adminauth', 'except' => array('/admin/login', '/admin/logout')), function() {
Route::resource('/admin/courses', 'CoursesController');
Route::resource('/admin/teachers', 'TeachersController');
Route::resource('/admin/subjects', 'SubjectsController');
});
Here is code of CoursesController.php file
<?php
class CoursesController extends BaseController
{
public function index()
{
$courses = Course::where('is_deleted', 0)->get();
return View::make('admin.courses.index', compact('courses'));
}
public function create()
{
return View::make('admin.courses.create');
}
public function store()
{
$validator = Validator::make($data = Input::all(), Course::$rules);
if ($validator->fails()) {
$messages = $validator->messages();
$response = '';
foreach ($messages->all(':message') as $message) {
$response = $message;
}
return Response::json(array('message'=>$response, 'status'=>'failure'));
} else {
Course::create($data);
return Response::json(array('message'=>'Course created successfully','status'=>'success'));
}
}
public function edit($id)
{
$course = Course::find($id);
return View::make('admin.courses.edit', compact('course'));
}
public function update($id)
{
$course = Course::findOrFail($id);
$validator = Validator::make($data = Input::all(), Course::editRules($id));
if ($validator->fails()) {
$messages = $validator->messages();
$response = '';
foreach ($messages->all(':message') as $message) {
$response = $message;
}
return Response::json(array('message'=>$response, 'status'=>'failure'));
} else {
$course->update($data);
return Response::json(array('message'=>'Course updated successfully','status'=>'success'));
}
}
public function destroy($id)
{
Course::findOrFail($id)->update(array('is_deleted' => '1'));
return Response::json(array('message'=>'Course deleted successfully','status'=>'success'));
}
}
Did you add autoload classmap to composer.json file?
Open your composer.json file and add
"autoload": {
"classmap": [
"app/controllers/admin",
]
}
if you add folders inside controllers, you need to add it to composer.json file. Then run
composer dumpautoload
OR ALTERNATIVE
go to app/start/global.php and add
ClassLoader::addDirectories(array(
app_path().'/controllers/admin',
));
2021 answer (Laravel 8.5)
In your controller;
namespace App\Http\Controllers;
use App\Http\Controllers\Controller;
use App\Providers\RouteServiceProvider;
use Illuminate\Http\Request;
class AuthController extends Controller
{
public function login(Request $request){
return "login";
}
}
In your routes;
use App\Http\Controllers\AuthController;
Route::post('/login', [AuthController::class, 'login']);
Doc = https://laravel.com/docs/8.x/routing#the-default-route-files
In my case, in the top of my controller code i add this line :
namespace App\Http\Controllers\CustomFolder\ControllerClassName;
and my problem is solved
We can create controller via command line.
php artisan make:controller nameController --plain.
Before Laravel 5, make namespace is not available. Instead, this works
php artisan controller:make nameController
Execute your command inside your project directory and then create your function.
Don't forget to do:
php artisan route:clear
In my case this was the solution when I got this error after making a route code change.
In my case, I had to change the route file from this:
Route::get('/','SessionController#accessSessionData');
to this:
Route::get('/','App\Http\Controllers\SessionController#accessSessionData');
then clearing the cache with this:
php artisan route:clear
made things work.
A bit late but in my experience adding this to the RouteServiceProvider.php solves the problem
protected $namespace = 'App\Http\Controllers';
I think your problem has already been fixed. But this is what did.
Structure
Http
.Auth
.CustomControllerFolder
-> CustomController.php
to get this working
in your route file make sure you use the correct name space
for eg:
Route::group(['namespace'=>'CustomControllerFolder','prefix'=>'prefix'],
function() {
//define your route here
}
Also dont forget to use namespace App\Http\Controllers\CustomControllerFolder in your controller.
That should fix the issue.
Thanks
I just had this issue because I renamed a file from EmployeeRequestContoller to EmployeeRequestsContoller, but when I renamed it I missed the .php extension!
When I reran php artisan make:controller EmployeeRequestsContoller just to be sure I wasn't going crazy and the file showed up I could clearly see the mistake:
/EmployeeRequestsContoller
/EmployeeRequestsContoller.php
Make sure you have the extension if you've renamed!
I use Laravel 9 this is the way we should use controllers
use App\Http\Controllers\UserController;
Route::get('/user', [UserController::class, 'index']);
Sometimes we are missing namespace App\Http\Controllers; on top of our controller code.
In my case, I have several backup files of admin and home controllers renamed with different dates and we ran a composer update on top of it and it gave us an error
after I removed the other older controller files and re-ran the composer update fixed my issue.
- Clue - composer update command gave us a warning.
Generating optimized autoload files
Warning: Ambiguous class resolution, "App\Http\Controllers\HomeController" was found in both "app/core/app/Http/Controllers/HomeController(25-OCT).php" and "app/core/app/Http/Controllers/HomeController.php", the first will be used.
Warning: Ambiguous class resolution, "App\Http\Controllers\AdminController" was found in both "app/core/app/Http/Controllers/AdminController(25-OCT).php" and "app/core/app/Http/Controllers/AdminController.php", the first will be used.
Use full namespace inside web.php
Route::resource('myusers','App\Http\Controllers\MyUserController');

Resources