Laravel: Controller does not exist - laravel-4

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');

Related

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);
}

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

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

Error on finding controller from Laravel API Router

I created a fresh Laravel framework.
I created a controller named PostsController:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Post;
use App\Http\Controllers\Controller;
class PostsController extends Controller
{
public function index()
{
$posts = Post::get();
return response()->success(compact('posts'));
}
}
Then I created a route in the file api.php:
Route::get('posts', 'PostsController#index');
I ran the command
$ php artisan serve`
and I tested the URL
localhost:8000/api/posts
This error occurs:
BadMethodCallException
Method Illuminate\Routing\ResponseFactory::success does not exist.
file: vendor/laravel/framework/src/Illuminate/Support/Traits/Macroable.php
line: 100
throw new BadMethodCallException("Method {$class}::{$method} does not exist.");
I can't understand why this happened. Please help me.
There is no success method on the ResponseFactory. You can find the available methods here.
You are calling a macro function that is not registerd to the responseFactory.To use success method,Create your custom responseServiceProvider and write this inside boot()
Response::macro('success',function($data){
return Response::json([
'data'=>$data,
]) ;
});
And then register your ResponseServiceProvider to app.php by adding your Class name to the array called providers. This is how you add to the array
App\Providers\ResponseMacroServiceProvider::class

Is it possible with laravel to go from post.store to post.edit?

I can't figure out how to go from a store method directly to a edit page.
Routes:
Route::post('/', 'PostController#store')->name('posts.store');
Route::get('/', 'PostController#edit')->name('posts.edit');
post controller:
public function store(Request $request)
{
$post = new Post;
$post->save();
return view('posts.edit');
}
public function edit($id)
{
dd('edit post');
}
I keep getting view not found or other errors. I have checked php artisan route:list and the correct route is there. What am i missing here?
Well you should do a redirect to the route instead. See Redirecting to Named Routes
So this should work:
return redirect()->route('posts.edit');
At this point, you are trying to load a view.

Laravel 5 add back routes.php NotFoundHttpException

In the last update to to Laravel 5 they removed the routes.php file in favor of Annotations. I still wish to use the routes.php file though. I read that you simple create the file in app/Http/routes.php and uncomment
//require app_path('Http/routes.php');
Inside the RouteServiceProvider.php file. I tried and I still get the NotFoundHttpException. For the following route.
Route::get('/', 'PagesController#home');
Inside the PagesController
<?php namespace App\Http\Controllers;
class PagesController {
public function home()
{
return 'test';
}
}
Can anyone tell me how to re enable it?
After uncommenting //require app_path('Http/routes.php'); you need to run:
php artisan clear-compiled
Otherwise your RouteServiceProvider is compiled and Laravel won't see the change you made in this file source

Resources