Home > Mobile >  Laravel - 404 | Not Found upon "/{id}" entry
Laravel - 404 | Not Found upon "/{id}" entry

Time:10-13

I am getting a "404 | Not Found" error when i try to access a specific item from my database. The items with the specific ID's do exist in the database, but i am not even sure if that even has any influence on the problem.

My routing looks likes this:

Route::prefix('departments')->group(function() {
Route::get('/{id}', [DepartmentController::class, 'showDepartment']);
});

And the related controller looks like this:

public function showDepartment() {
        return '';
    }

}

I haven't yet finished the function. I just wanted to check if the routing even worked by returning an empty string.

So what am i doing wrong? Is it the routing or the controller?

CodePudding user response:

According to the Laravel documentation, you have to define the parameter in the route then use it in the controller as a parameter. in your controller:

public function showDepartment($id) {
    return 'Hello';
}

The id is not bound to any model to fetch from the database to do that you can use Laravel route model binding

for example when you have a model named Department you write your route like this:

Route::get('/{department}', [DepartmentController::class, 'showDepartment']);

and in the controller:

public function showDepartment(Department $department) {
    return 'Hello from depratment';
}

When your department exists it returns the response otherwise return 404.

CodePudding user response:

You may need a Department model class. Then you can find the item from database by id $department = Department::findOrFail($id);

CodePudding user response:

you are send parameter in route and this function without any parameter route :

Route::prefix('departments')->group(function() {
Route::get('/{id}', [DepartmentController::class, 'showDepartment']);
});

your function in controller should be

public function showDepartment($id) {

        $department = Department::findOrFail($id);
    }

}
  • Related