skip to Main Content

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

2

Answers


  1. 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'); 
    }  
    

    }

    Login or Signup to reply.
  2. 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
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search