使用 laravel + vue3 建立短網址(short url)的程式範例

下面是一個完整、可實作的範例,示範如何用 Laravel(API)+ Vue 3(前端) 建立一個「短網址(Short URL)系統」。

後端用 Laravel 架構風格來寫(Controller + Migration),前端用 Vue 3 Composition API + Axios

操作畫面

網址: https://twingo.polinwei.com/pages/ShortUrl

image 9

架構總覽

CSS
Frontend (Vue 3)
  └─ 輸入長網址 → 呼叫 API → 顯示短網址

Backend (Laravel)
  ├─ POST /api/short-urls     建立短網址
  ├─ GET  /{code}             轉址
  └─ short_urls table

一、Laravel 後端

先建立後端 Laravel 必要程式

Migration: 建立資料表

Bash
php artisan make:migration create_short_urls_table

修改 table schema: short_urls

PHP
return new class extends Migration
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {   // 短網址
        Schema::create('short_urls', function (Blueprint $table) {
            $table->id();
            $table->string('original_url', 2048)->comment('原始網址');
            $table->string('code', 10)->unique()->comment('短網址代碼');
            $table->unsignedBigInteger('clicks')->default(0)->comment('點擊次數');
            $table->timestamp('expired_at')->nullable()->comment('過期時間');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::dropIfExists('short_urls');
    }
};

建立表格

Bash
php artisan migrate

Model: ShortUrl

PHP
class ShortUrl extends Model
{
    // 指定資料表名稱
    protected $table = 'short_urls';
    // 可批量賦值的屬性
    protected $fillable = [
        'original_url',
        'code',
        'clicks',
        'expired_at',
    ];
}

API Controller: ShortUrlController(建立短網址)

建立控制器 ShortUrlController

Bash
php artisan make:controller Api/ShortUrlController

程式碼內容

PHP
namespace App\Http\Controllers\Api;

use App\Models\ShortUrl;
use Illuminate\Http\Request;
use Illuminate\Support\Str;

class ShortUrlController extends Controller
{
    public function store(Request $request)
    {
        $request->validate([
            'url' => ['required', 'url'],
        ]);

        do {
            $code = Str::random(6);
        } while (ShortUrl::where('code', $code)->exists());

        $shortUrl = ShortUrl::create([
            'original_url' => $request->url,
            'code' => $code,
        ]);

        return response()->json([
            'short_url' => url($shortUrl->code),
            'code' => $code,
        ]);
    }
}

Redirect Controller(短網址轉址)

建立轉址的控制器: RedirectController

Bash
php artisan make:controller RedirectController

程式碼內容

PHP
namespace App\Http\Controllers;

use App\Models\ShortUrl;

class RedirectController extends Controller
{
    public function __invoke(string $code)
    {
        $shortUrl = ShortUrl::where('code', $code)->firstOrFail();

        $shortUrl->increment('clicks');

        return redirect()->away($shortUrl->original_url);
    }
}

Routes 路由

PHP
// 檔案: routes/api.php

Route::post('/short-urls', [\App\Http\Controllers\Api\ShortUrlController::class, 'store']);
PHP
// 檔案: routes/web.php
Route::get('/{code}', \App\Http\Controllers\RedirectController::class)
    ->where('code', '[A-Za-z0-9]+');

二、Vue 3 前端

再來是前端畫面的呈現

Axios API 封裝

PHP
// 檔案: src/api/shortUrl.js

import axios from 'axios'

export function createShortUrl(url) {
  return axios.post('/api/short-urls', {
    url,
  })
}

Composable: useShortUrl.js

TypeScript
// 檔案: src/composables/useShortUrl.js

import { ref } from 'vue'
import { createShortUrl } from '@/api/shortUrl'

export function useShortUrl() {
  const loading = ref(false)
  const shortUrl = ref('')
  const error = ref('')

  const generate = async (url) => {
    loading.value = true
    error.value = ''

    try {
      const { data } = await createShortUrl(url)
      shortUrl.value = data.short_url
    } catch (e) {
      error.value = '建立短網址失敗'
    } finally {
      loading.value = false
    }
  }

  return {
    loading,
    shortUrl,
    error,
    generate,
  }
}

Vue 頁面

Vue
// 檔案: ShortUrlPage.vue

<script setup>
import { ref } from 'vue'
import { useShortUrl } from '@/composables/useShortUrl'

const url = ref('')
const { generate, shortUrl, loading, error } = useShortUrl()
</script>

<template>
  <div>
    <h2>短網址產生器</h2>

    <input
      v-model="url"
      placeholder="請輸入長網址"
    />

    <button :disabled="loading" @click="generate(url)">
      產生
    </button>

    <p v-if="shortUrl">
      短網址:
      <a :href="shortUrl" target="_blank">
        {{ shortUrl }}
      </a>
    </p>

    <p v-if="error" style="color:red">{{ error }}</p>
  </div>
</template>

總結

✔ Laravel 負責:產碼、儲存、轉址
✔ Vue 3 負責:UI + API 呼叫
✔ 架構清楚、可擴充、可商用

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *


內容索引