Home > Software design >  laravel dynamic routing showing 404 not found
laravel dynamic routing showing 404 not found

Time:02-02

I have created a route to pass dynamic parameters to controller but when i serve url it shows me for not found here is my route and controller I create

Routes

Route::get('/admin/managers/{method}/{id}', 
    [
        SetupController::class, 'managers'
    ]
);

Controller

public function managers($method, $id) {
        if($method == 'create') {
            return view('admin.pages.create-manager'); 
        } elseif($method == 'create') {
            echo $id;
            return view('admin.pages.create-manager'); 
        } else {
            return view('admin.pages.managers'); 
        }  
    }

When i serve url localhost/public/managers it shows me 404 not found but when i serve localhost/public/managers/create/1 the page is loading then can anyone hep me out why exactly is it happening

CodePudding user response:

as we discussed in the comments what you need is to make your parameters optional like below

change your route like this

    Route::get('/admin/managers/{method?}/{id?}', [SetupController::class, 'managers']);

and your controller like this

public function managers($method=null, $id=null) {
    if ($method == 'create') {
        return view('admin.pages.create-manager'); 
    } elseif ($method == 'edit') { // change here
        echo $id;
        return view('admin.pages.create-manager'); 
    } else {
        return view('admin.pages.managers'); 
    }  
}

and also don't forget to run at the end

php artisan optimize

CodePudding user response:

The issue is that in your code, the second if condition is checking for the same value 'create', this resulting in a 404 error for the URL "localhost/public/managers".

To resolve this issue, change the second if condition to check for another value. For example, if you want to show the page with the id, use the following code:

public function managers($method, $id) {
if ($method == 'create') {
    return view('admin.pages.create-manager'); 
} elseif ($method == 'show') {//or anything else
    echo $id;
    return view('admin.pages.create-manager'); 
} else {
    return view('admin.pages.managers'); 
}  

}

CodePudding user response:

The problem is in if ($method == 'create') but the same condition is already there in the first if statement.

So your managers function should be like:

public function managers($method=null, $id=null) {
    if ($method == 'create') {
        return view('admin.pages.create-manager'); 
    } elseif ($method == 'edit') { // change here
        echo $id;
        return view('admin.pages.create-manager'); 
    } else {
        return view('admin.pages.managers'); 
    }  
}

In your Route:

Route::get('/admin/managers/{method?}/{id?}', [SetupController::class, 'managers'])->where(['method' => '(create|edit)', 'id' => '[0-9] ']);
  • Related