如何使用Laravel实现前后端api分离

一、创建路由文件:

  • 在routes文件夹下创建两个文件:api.php(用于前台API)和admin.php(用于后台API)。

二、定义路由:

  • 在api.php中定义前台API的路由:
// routes/api.php
Route::get('posts', 'Api\PostController@index');
Route::post('posts', 'Api\PostController@store');
// 其他前台API路由...
  • 在admin.php中定义后台API的路由:
// routes/admin.php
Route::get('admin/posts', 'Admin\Api\PostController@index');
Route::post('admin/posts', 'Admin\Api\PostController@store');
// 其他后台API路由...

三、注册路由文件

  • 在RouteServiceProvider中注册新建的路由文件:
// app/Providers/RouteServiceProvider.php

protected function mapApiRoutes()
{
    $this->mapApiFrontendRoutes();
    $this->mapApiAdminRoutes();
}

protected function mapApiFrontendRoutes()
{
    Route::prefix('api')
        ->middleware('api')
        ->namespace($this->namespace)
        ->group(base_path('routes/api.php'));
}

protected function mapApiAdminRoutes()
{
    Route::prefix('api')
        ->middleware(['api', 'auth', 'admin']) // 根据需要添加后台认证中间件
        ->namespace($this->namespace)
        ->group(base_path('routes/admin_api.php'));
}

可以根据需要为前后台API分别设置中间件和认证,确保安全性和权限控制。

Logo

加入社区!打开量化的大门,首批课程上线啦!

更多推荐