Home > Mobile >  Function() does not exist error using php Laravel controllers and router
Function() does not exist error using php Laravel controllers and router

Time:12-16

I have a router web.php and two controllers. One is HomeController with my index/homepage, and the other is InventoryController with a randomly generated database. I am currently getting an error when I run it on localhost that there is a "Reflection Exception and that the Function() does no exist".

My router web.php:

<?php

use Illuminate\Support\Facades\Route;

Route::get('/', [\App\Http\Controllers\HomeController::class], 'pages.index');

Route::get('/inventories', [\App\Http\Controllers\InventoryController::class], 'index');
{
    return View('pages.inventories');
};

My HomeController code:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

/**
 *
 */
class HomeController extends Controller
{
    public function index() {
        return view('pages.index');
    }
}

My InventoryController code:

<?php

namespace App\Http\Controllers;

use App\Models\Inventory;
use Illuminate\Http\Request;

/**
 *
 */

class InventoryController extends Controller
{
    public function index() {
        $inventories = Inventory::all();
        return view('pages.inventories',[
            "inventories" => $inventories
        ]);
    }
}

I know I do not want to use __invoke() because future features and content will be added.

CodePudding user response:

Route::get('/', [\App\Http\Controllers\HomeController::class, 'index']);

Route::get('/inventories', [\App\Http\Controllers\InventoryController::class, 'index']);

and also the second parameter should be massive In the controller name method name is index and not pages.index

CodePudding user response:

You misused your router definition, you need to define the second parameter of the array, to be the function on the controller it should hit.

Route::get('/', [\App\Http\Controllers\HomeController::class, 'index'])->name('pages.index');
Route::get('/inventories', [\App\Http\Controllers\InventoryController::class, 'index'])->name('index'');

It seems like you also use the third parameter as naming eg. pages.index i would use the ->name() call instead.

CodePudding user response:

You can write like this,

<?php

use Illuminate\Support\Facades\Route;

Route::get('/', [ 
    \App\Http\Controllers\HomeController::class, 
    'pages.index' 
]);
  • Related