【问题标题】:Laravel - Making Routes in file other than web.phpLaravel - 在 web.php 以外的文件中创建路由
【发布时间】:2021-06-26 07:45:44
【问题描述】:

在 web.php 中对网站的各个页面进行路由会使其体积庞大且非结构化。所以我的问题是有没有办法将它保存在单独的文件中?

// Calling Registration function
Route::any('/admin-store','AdminUserController@store')->name('admin-reg'); 

// Redirecting to Registration page
Route::get('/admin-registration','AdminUserController@index')->name('admin-registration'); 

// Redirecting to login page
Route::get('/admin-login','AdminLoginController@index')->name('admin-login'); 

// Redirecting to Admin Profile Page
Route::get('/admin-profile','AdminProfileController@index')->name('admin-profile'); 

// Calling Login function
Route::post('admin-login-result','AdminLoginController@login')->name('admin-log'); 

// Calling Function to Update Profile
Route::post('admin-edit-profile','AdminEditController@updateProfile')
         ->name('admin-edit-profile'); 

// Redirecting to Profile Edit page
Route::get('/admin-edit-profile','AdminEditController@index')->name('admin-edit'); 

【问题讨论】:

标签: laravel laravel-5


【解决方案1】:

简答

是的,您可以将路线存储在不同的文件中。


扩展答案

1 - 创建您的新路线文件

创建您的新路由文件,在本例中,我将其命名为 users.php 并在其中存储相关路由:

  • routes/users.php
  Route::get('/my-fancy-route', 'MyCoolController@anAwesomeFunction');
  // and the rest of your code.

2 - 将您的路由文件添加到 RouteServiceProvider

在这里添加一个新方法,我称之为mapUserRoutes

  • app/Providers/RouteServiceProvider.php
/**
 * Define the User routes of the application.
 *
 *
 * @return void
 */
protected function mapUserRoutes()
{
    Route::prefix('v1')  // if you need to specify a route prefix
        ->middleware('auth:api') // specify here your middlewares
        ->namespace($this->namespace) // leave it as is
        /** the name of your route goes here: */
        ->group(base_path('routes/users.php'));
}

3 - 将其添加到 map() 方法中

在同一个文件(RouteServiceProvider.php) 中,转到顶部并在map() 函数中添加新方法:

/**
 * Define the routes for the application.
 *
 * @return void
 */
public function map()
{

    // some other mapping actions

    $this->mapUserRoutes();
}

4 - 最后步骤

我不完全确定这是否有必要,但这样做永远不会有坏处:

  • 停止你的服务器(如果正在运行)

  • php artisan config:clear

  • 启动你的服务器。

【讨论】:

  • 得到错误:类 excel(我的新路由文件的名称)不存在
  • 你更新->group(base_path('path/to/route/file.php'));了吗?
猜你喜欢
  • 1970-01-01
  • 2018-12-22
  • 2021-02-03
  • 1970-01-01
  • 2017-04-27
  • 1970-01-01
  • 2019-04-25
  • 1970-01-01
  • 2019-12-06
相关资源
最近更新 更多