You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Laravel、Vue.js与Flutter协同方案及后端复用、鉴权咨询

统一Laravel后端支持Web与Flutter应用 + 认证方案建议

Great question! Let’s tackle this step by step—you’re right to avoid duplicate controller code, and there are clean ways to unify your backend while keeping everything in a single repo.

一、避免重复代码:统一后端逻辑

Instead of copying controllers to an API/ directory, you can reuse your existing business logic and dynamically return responses based on the request type (web view vs. JSON for Flutter). Here are two solid approaches:

1. 用资源类(Resources)+ 请求类型判断

Laravel’s API Resources let you define a single data structure that works for both web views and JSON responses. Then, check if the request expects JSON (Flutter will send Accept: application/json headers) and return the appropriate response:

use App\Http\Resources\PostResource;
use App\Models\Post;

public function show(Post $post)
{
    // 统一数据结构
    $postData = PostResource::make($post)->resolve();

    // 根据请求类型返回响应
    if (request()->expectsJson()) {
        return response()->json($postData);
    }

    return view('posts.show', $postData);
}

2. 抽离业务逻辑到动作类(Actions)

For more complex logic, extract core business logic into action classes—this way, both web and API controllers call the same code, eliminating duplication entirely:

First, create an action class:

// app/Actions/FetchPostAction.php
namespace App\Actions;

use App\Models\Post;

class FetchPostAction
{
    public function execute(Post $post)
    {
        // 这里放所有业务逻辑:关联数据加载、权限检查等
        return $post->load(['comments', 'author']);
    }
}

Then use it in your controller:

public function show(Post $post)
{
    $postData = app(FetchPostAction::class)->execute($post);
    
    return request()->expectsJson()
        ? response()->json(PostResource::make($postData))
        : view('posts.show', ['post' => $postData]);
}

This keeps your controllers thin and ensures your business logic is only written once.

二、前后端同仓部署

Since your web app is Laravel (no Vue) and Flutter is mobile, you can easily keep everything in a single repo by organizing your directory structure like this:

your-project/
├── app/                  # Laravel核心代码
├── bootstrap/
├── config/
├── flutter-app/          # Flutter移动端项目
│   ├── android/
│   ├── ios/
│   ├── lib/
│   └── pubspec.yaml
├── public/
├── resources/
├── routes/
└── ... 其他Laravel目录

部署注意事项:

  • Laravel backend: Deploy as usual to your web server (Apache/Nginx, PHP, MySQL).
  • Flutter app: Build the APK/IPA locally or via CI/CD, then distribute to app stores. If you ever build a Flutter web version, you can deploy it to a subdirectory or subdomain of your Laravel server.
  • Git management: Commit both Laravel and Flutter code to the same repo—add any Flutter-specific ignores (like .dart_tool/) to your root .gitignore.

三、认证方案选择:Passport vs JWT vs Sanctum (Airlock)

Let’s break down which fits your use case best:

🎯 优先选择:Laravel Sanctum (原Airlock)

This is the perfect fit for your scenario because:

  • Dual support: Works seamlessly with Laravel’s default session authentication (for your existing web app) and API token authentication (for Flutter mobile).
  • Lightweight: No heavy OAuth2 setup—just install the package, run migrations, and configure guards.
  • Easy integration: For Flutter, users log in via your Laravel API, receive a token, and include it in subsequent requests with the Authorization: Bearer {token} header. Your web app continues using standard session cookies with zero changes.
  • Security: Sanctum handles token revocation, CSRF protection for SPAs (if you ever add Vue later), and supports token expiration.

🧐 备选:JWT (e.g., tymon/jwt-auth)

JWT is a good choice if you need stateless API authentication, but it’s less ideal for your unified backend:

  • You’ll need separate authentication logic for your web app (session-based) and Flutter (JWT-based), which adds minor overhead.
  • Configuration is more manual compared to Sanctum, and you’ll have to handle token refresh logic yourself.
  • It doesn’t integrate with Laravel’s native session system out of the box.

❌ 不推荐:Laravel Passport

Passport is a full OAuth2 server, which is overkill for your use case:

  • It’s designed for scenarios where you need to allow third-party apps to access your API (like login with Google/Facebook for your service).
  • Setup is complex, and it adds unnecessary layers of abstraction when you only need to support your own web and Flutter apps.

Final Recommendations

  1. Use action classes + resources to unify your backend logic and avoid duplicate code.
  2. Organize your repo with Laravel at the root and Flutter in a subdirectory for easy同仓维护.
  3. Go with Laravel Sanctum for authentication—it’s the simplest, most integrated solution for your needs.

内容的提问来源于stack exchange,提问作者Jospy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.06 22:12:39