Home > front end >  Laravel route resolving to a different method
Laravel route resolving to a different method

Time:02-23

I'm trying to set up a basic Laravel CRUD application, and I'm getting stuck setting up the pages for each action.

When I visit the route case/create, it opens the page for show instead.

routes/web.php

use App\Http\Controllers\HospitalCase as HospitalCase;

Route::controller(HospitalCase::class)->group(function() {
    Route::get('/cases','index')->middleware('auth')->name('cases');
    Route::get('/case/{id}','show')->middleware('auth');
    Route::get('/case/create','create')->middleware('auth');
    Route::post('/case/create','store')->middleware('auth');
    Route::get('/case/edit/{$id}','edit')->middleware('auth');
    Route::post('/case/edit/{$id}','update')->middleware('auth');
    Route::get('/case/delete/{$id}','destroy')->middleware('auth');
});

HospitalCase.php controller

class HospitalCase extends Controller
{
    function index()
    {
        echo 'index';
    }

    function create()
    {
        echo 'create';
    }

    function show($id)
    {
        echo 'show';
    }

    function store()
    {
        // validation rules
    }

    function edit($id)
    {
        return view('case/edit');
    }

    function update($id)
    {
    }

    function destroy($id)
    {
    }
}

This is what I see on the browser:

I have been trying to figure this out for hours and can't think of what I'm doing wrong.

PS: The auth middleware is using laravel breeze (unmodified)

CodePudding user response:

The reason it's showing the show route is because you defined

Route::get('/case/{id}','show')->middleware('auth');

before it, therefore, it's matching case/create as show('create')

Try defining the route afterwards.

Route::get('/case/create','create')->middleware('auth');
Route::post('/case/create','store')->middleware('auth');
Route::get('/case/{id}','show')->middleware('auth');

CodePudding user response:

Just want to reiterate what @TimLewis has suggested, I think you need to put this route:

Route::get('/case/create','create')->middleware('auth');

Above this route:

Route::get('/case/{id}','show')->middleware('auth');

But you could try using Laravel’s route resource so you don’t need to write out all the routes -

use App\Http\Controllers\HospitalCaseController;

Route::resource('cases', HospitalCaseController::class);
  • Related