I can't get the Controller in the laravel

Viewed 1380

I have a problem accessing a Controller that I created via terminal:

php artisan make:controller Admin\TestController

This is the TestController class I created

<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;

class TestController extends Controller
{
    public function teste()
    {
        return 'Teste Controller';
    }
}

Here is the routes file, where I will try to call the teste method. By default, the correct thing would be to call the TestController in the Admin folder.

<?php

use Illuminate\Support\Facades\Route;

Route::get('/test', 'Admin\TestController@teste');

In the Web.php file when I update the page, the message appears:

Illuminate\Contracts\Container\BindingResolutionException Target class
[Admin\TestController] does not exist.

It only works when I put the full directory:

<?php

use Illuminate\Support\Facades\Route;

Route::get('/test', 'App\Http\Controllers\Admin\TestController@teste');

But I did not want to put the complete directory for reasons of a leaner code and easy to understand.

How can I call the TestController without placing the complete directory?

I'm using the Laravel Framework: 8.9.0

I'm using php: 7.2.19 (cli)

3 Answers

According to the upgrade documentation of Laravel 8, you can use PHP callable syntax like this way :

use App\Http\Controllers\Admin\TestController;

Route::get('/test', [TestController::class, 'teste']);

this is because of the latest version of Laravel that you are using. Read the documentation for the latest Laravel version here!

Yupp, as mentioned above, for the new Laravel Version 8.x, in the routes.php, you have to mention the controller class as in array format, for example

<?php
use App\Http\Controllers\Controller_Name;

Route::get('/', [Controller_Name::class,'Function_Name']); ?>

Also don't forget to import that controller class.

Here's link for Laravel 8.x referring the routing.

Hope it helps. Thank You

Related