HackMD
    • Sharing Link copied
    • /edit
    • View mode
      • Edit mode
      • View mode
      • Book mode
      • Slide mode
      Edit mode View mode Book mode Slide mode
    • Note Permission
    • Read
      • Only me
      • Signed-in users
      • Everyone
      Only me Signed-in users Everyone
    • Write
      • Only me
      • Signed-in users
      • Everyone
      Only me Signed-in users Everyone
    • More (Comment, Invitee)
    • Publishing
    • Commenting Enable
      Disabled Forbidden Owners Signed-in users Everyone
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Invitee
    • No invitee
    • Options
    • Versions
    • Transfer ownership
    • Delete this note
    • Template
    • Save as template
    • Insert from template
    • Export
    • Google Drive Export to Google Drive
    • Gist
    • Import
    • Google Drive Import from Google Drive
    • Gist
    • Clipboard
    • Download
    • Markdown
    • HTML
    • Raw HTML
Menu Sharing Help
Menu
Options
Versions Transfer ownership Delete this note
Export
Google Drive Export to Google Drive Gist
Import
Google Drive Import from Google Drive Gist Clipboard
Download
Markdown HTML Raw HTML
Back
Sharing
Sharing Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Note Permission
Read
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Write
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
More (Comment, Invitee)
Publishing
More (Comment, Invitee)
Commenting Enable
Disabled Forbidden Owners Signed-in users Everyone
Permission
Owners
  • Forbidden
  • Owners
  • Signed-in users
  • Everyone
Invitee
No invitee
   owned this note    owned this note      
Published Linked with
Like BookmarkBookmarked
Subscribed
  • Any changes
    Be notified of any changes
  • Mention me
    Be notified of mention me
  • Unsubscribe
Subscribe
以下是以 Laravel 框架實作討論區專案的關鍵程式碼與說明: --- ## 一、資料庫設計與遷移 ```php // database/migrations/xxxx_create_users_table.php Schema::create('users', function (Blueprint $table) { $table->id(); $table->string('name'); $table->string('email')->unique(); $table->string('password'); $table->string('avatar')->nullable(); $table->enum('role', ['admin', 'forum_admin', 'user'])->default('user'); $table->text('bio')->nullable(); $table->timestamps(); }); // database/migrations/xxxx_create_forums_table.php Schema::create('forums', function (Blueprint $table) { $table->id(); $table->string('name'); $table->text('description'); $table->timestamps(); }); // database/migrations/xxxx_create_posts_table.php Schema::create('posts', function (Blueprint $table) { $table->id(); $table->string('title'); $table->text('content'); $table->foreignId('forum_id')->constrained(); $table->foreignId('user_id')->constrained(); $table->string('image')->nullable(); $table->timestamps(); }); ``` **關聯說明**: - `User` 與 `Post`: 一對多 (`hasMany()`) - `Forum` 與 `Post`: 一對多 (`hasMany()`) - `Post` 與 `User/Forum`: 反向關聯 (`belongsTo()`) --- ## 二、模型與關聯 ```php // app/Models/User.php class User extends Authenticatable { public function posts() { return $this->hasMany(Post::class); } } // app/Models/Forum.php class Forum extends Model { public function posts() { return $this->hasMany(Post::class); } } // app/Models/Post.php class Post extends Model { public function user() { return $this->belongsTo(User::class); } public function forum() { return $this->belongsTo(Forum::class); } } ``` --- ## 三、中介層權限檢查 ```php // app/Http/Middleware/CheckAdmin.php public function handle($request, Closure $next) { if (!auth()->check() || !in_array(auth()->user()->role, ['admin', 'forum_admin'])) { return redirect('/')->with('error', '權限不足'); } return $next($request); } ``` 註冊中介層: ```php // app/Http/Kernel.php protected $routeMiddleware = [ 'admin' => \App\Http\Middleware\CheckAdmin::class, ]; ``` --- ## 四、控制器邏輯範例 ### 會員註冊 (使用 Laravel Breeze 擴充) ```php // app/Http/Controllers/Auth/RegisteredUserController.php protected function validator(array $data) { return Validator::make($data, [ 'name' => ['required', 'string', 'max:255'], 'email' => ['required', 'string', 'email', 'max:255', 'unique:users'], 'password' => ['required', 'string', 'min:8', 'confirmed'], ]); } ``` ### 文章發表邏輯 ```php // app/Http/Controllers/PostController.php public function store(Request $request) { $validated = $request->validate([ 'title' => 'required|max:255', 'content' => 'required', 'forum_id' => 'required|exists:forums,id', 'image' => 'nullable|image|mimes:jpeg,png,jpg,gif|max:2048' ]); if ($request->hasFile('image')) { $path = $request->file('image')->store('posts', 'public'); $validated['image'] = $path; } $post = auth()->user()->posts()->create($validated); return redirect()->route('posts.show', $post); } ``` --- ## 五、路由設定 ```php // routes/web.php // 會員功能 Route::middleware('guest')->group(function () { Route::get('register', [RegisteredUserController::class, 'create']); Route::post('register', [RegisteredUserController::class, 'store']); // 登入路由... }); // 文章功能 Route::resource('posts', PostController::class)->except(['index']); // 管理後台路由組 Route::middleware(['auth', 'admin'])->prefix('admin')->group(function () { Route::resource('forums', ForumAdminController::class); }); ``` --- ## 六、Blade 模板範例 ### 文章列表分頁 ```php // resources/views/posts/index.blade.php @foreach ($posts as $post) <div class="post"> <h2>{{ $post->title }}</h2> <p>{{ Str::limit($post->content, 100) }}</p> </div> @endforeach {{ $posts->links() }} // 分頁連結 ``` ### 圖片上傳表單 ```html <form method="POST" enctype="multipart/form-data"> @csrf <input type="file" name="image"> <!-- 其他表單欄位 --> </form> ``` --- ## 七、圖片儲存設定 ```php // config/filesystems.php 'disks' => [ 'public' => [ 'driver' => 'local', 'root' => storage_path('app/public'), 'url' => env('APP_URL').'/storage', 'visibility' => 'public', ], ] ``` 執行指令建立符號連結: ```bash php artisan storage:link ``` --- ## 補充說明 1. 權限系統可透過 Policy 進一步細化控制 2. 圖片上傳建議使用雲端儲存服務(如 S3)時需修改 filesystems 設定 3. 前端樣式可使用 Tailwind CSS 或 Bootstrap 快速搭建 4. API 開發可使用 Laravel Sanctum 進行認證 以上程式碼展示了主要功能模組的實作方式,實際開發時需根據需求補充驗證邏輯、錯誤處理與安全性措施。

Import from clipboard

Advanced permission required

Your current role can only read. Ask the system administrator to acquire write and comment permission.

This team is disabled

Sorry, this team is disabled. You can't edit this note.

This note is locked

Sorry, only owner can edit this note.

Reach the limit

Sorry, you've reached the max length this note can be.
Please reduce the content or divide it to more notes, thank you!

Import from Gist

Import from Snippet

or

Export to Snippet

Are you sure?

Do you really want to delete this note?
All users will lost their connection.

Create a note from template

Create a note from template

Oops...
This template has been removed or transferred.


Upgrade

All
  • All
  • Team
No template.

Create a template


Upgrade

Delete template

Do you really want to delete this template?

This page need refresh

You have an incompatible client version.
Refresh to update.
New version available!
See releases notes here
Refresh to enjoy new features.
Your user state has changed.
Refresh to load new user state.

Sign in

Forgot password

or

Sign in via GitHub

New to HackMD? Sign up

Help

  • English
  • 中文
  • 日本語

Documents

Tutorials

Book Mode Tutorial

Slide Example

YAML Metadata

Resources

Releases

Blog

Policy

Terms

Privacy

Cheatsheet

Syntax Example Reference
# Header Header 基本排版
- Unordered List
  • Unordered List
1. Ordered List
  1. Ordered List
- [ ] Todo List
  • Todo List
> Blockquote
Blockquote
**Bold font** Bold font
*Italics font* Italics font
~~Strikethrough~~ Strikethrough
19^th^ 19th
H~2~O H2O
++Inserted text++ Inserted text
==Marked text== Marked text
[link text](https:// "title") Link
![image alt](https:// "title") Image
`Code` Code 在筆記中貼入程式碼
```javascript
var i = 0;
```
var i = 0;
:smile: :smile: Emoji list
{%youtube youtube_id %} Externals
$L^aT_eX$ LaTeX
:::info
This is a alert area.
:::

This is a alert area.

Versions

Versions

Upgrade now

Version named by    

More Less
  • Edit
  • Delete

Note content is identical to the latest version.
Compare with
    Choose a version
    No search result
    Version not found

Feedback

Submission failed, please try again

Thanks for your support.

On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

Please give us some advice and help us improve HackMD.

 

Thanks for your feedback

Remove version name

Do you want to remove this version name and description?

Transfer ownership

Transfer to
    Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.