Skip to main content

Laravel 8: Routing Change

 

In a fresh laravel 8 install, I have this in my web.php file:


    Route::get('/''HomeController@index');
 

and this in the index method of the HomeController.php

  
 
     /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        return view('welcome');
    }
 

 

error page:--

FireShot Capture 058 - 🧨 Target class [HomeController] does not exist. - localhost

 

The way to define your routes in laravel 8 or above is

 
    use App\Http\Controllers\HomeController;

    // Using PHP callable syntax...
    Route::get('/', [HomeController::class'index']);



OR

 
    // Using string syntax...
    Route::get('/''App\Http\Controllers\HomeController@index');
 

 
 If you want to stick to the old way, then you need to add a namespace property 
in the RouteServiceProvider.php (This property was present in previous versions)
 and activate in the routes method.
 
 
    /**
     * This namespace is applied to your controller routes.
     *
     * In addition, it is set as the URL generator's root namespace.
     *
     * @var string
     */
    protected $namespace = 'App\Http\Controllers';

    // Edit boot method  
    /**
     * Define your route model bindings, pattern filters, etc.
     *
     * @return void
     */
    public function boot()
    {
        $this->configureRateLimiting();

        $this->routes(function () {
            Route::middleware('web')
                ->namespace($this->namespace)
                ->group(base_path('routes/web.php'));

            Route::prefix('api')
                ->middleware('api')
                ->namespace($this->namespace)
                ->group(base_path('routes/api.php'));
    });
 
 in laravel 8 you can use the new syntax to define your routes or stick to the old way.
 
 

Comments

Popular posts from this blog

Laravel - Remove Public from URL using htaccess

  Step 1: Rename File In first step it is very easy and you need to just rename file name. you have to rename server.php to index.php at your laravel root directory. server.php INTO index.php   Step 2: Update .htaccess first of all you have to copy .htaccess file and put it laravel root folder. You just copy .htaccess file from public folder and then update bellow code: .htaccess Options -MultiViews -Indexes RewriteEngine On # Handle Authorization Header RewriteCond %{HTTP:Authorization} . RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}] # Redirect Trailing Slashes If Not A Folder... RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{REQUEST_URI} (.+)/$ RewriteRule ^ %1 [L,R=301] # Handle Front Controller... RewriteCond %{REQUEST_URI} !(\.css|\.js|\.png|\.jpg|\.gif|robots\.txt)$ [NC] RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{REQUEST_FILENAME} !-f RewriteRule ^ index.php [L] RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{REQUEST_FILENAME} !-f Re...