Home > Net >  Error with mapping out routes to controller classes in Laravel
Error with mapping out routes to controller classes in Laravel

Time:11-15

I am having an issue when trying to define my routes to controller classes in Laravel.

My web.php route looks like this:

use App\Http\Controllers\Frontend\ArticlesController as FrontEndArticlesController;
Route::get('/articles/{article:slug}', [FrontendArticlesController::class, 'show']);

The controller looks like this:

namespace App\Http\Controllers;
use App\Models\Article;
use Illuminate\Http\Request;
use Inertia\Inertia;

class ArticlesController extends Controller
{
    public function index() {
        $articles = Article::orderBy('created_at', 'desc')->paginate(5);
        return Inertia::render('Article/Index', compact('articles'));
    }

    public function show($slug)
    {
        $article = Article::where('slug', $slug)->firstOrFail();
        return Inertia::render('Article/Show', compact('article'));
    }

}

I keep getting the following errors no matter what I do, please help.

Cannot declare class App\Http\Controllers\ArticlesController, because the name is already in use

CodePudding user response:

Change your namespace in your controller;

namespace App\Http\Controllers\Frontend;

And use:

use App\Http\Controllers\Controller;

CodePudding user response:

Your class name already used anywhere and you only can use name App\Http\Controllers\ArticlesController class once. And second reason - maybe your class loader/reader (composer) saved it in draft/cache. Try this:

composer clear-cache

composer dump-autoload

Additionally, you should read about autoload: https://www.php.net/manual/en/language.oop5.autoload.php

  • Related