Search code examples
laravellaravel-9

Is there easyest way to change 'resouce' name in web.php [Laravel9]


I'm studying Laravel9 routing with sample code and I'm having problem changing URL. I would like to change URL as below

Currently I can access this URL

127.0.0.01:8000/student/

and

127.0.0.01:8000/student/create

but I would like to change like this

127.0.0.01:8000/fun_student/

and

127.0.0.01:8000/fun_student/create

I wrote like this

web.php

Route::prefix('fun_fun_student')->group(function (){
    Route::resource('students', StudentController::class);   
});

but I can't display as this URL. Could someone teach me correct code please?

UPDATE

I tried

Route::resource('fun', StudentController::class);

then my current route list

  GET|HEAD        fun ............................. fun.index › StudentController@index  
  POST            fun ............................. fun.store › StudentController@store  
  GET|HEAD        fun/create .................... fun.create › StudentController@create  
  GET|HEAD        fun/{fun} ......................... fun.show › StudentController@show  
  PUT|PATCH       fun/{fun} ..................... fun.update › StudentController@update  
  DELETE          fun/{fun} ................... fun.destroy › StudentController@destroy  
  GET|HEAD        fun/{fun}/edit .................... fun.edit › StudentController@edit 

Solution

  • To change the prefix of your resource. you have to change the resource name.

    Ex:

    Route::resource('fun_student', StudentController::class); 
    

    Then you can use routes like this:

    Ex:

    <a href="{{ route('fun_student.index') }}">Students</a>
    

    This route should output the following URL:

    http://127.0.0.01:8000/fun_student
    

    After the resource changed, remember to clear cache by running:

    php artisan route:clear
    // or
    php artisan optimize:clear
    

    Also change route('students.xxx') to route('fun_student.xxx') in other places in your project.

    I would suggest you go through the Laravel documentation for more information.