Physical Address
304 North Cardinal St.
Dorchester Center, MA 02124
Physical Address
304 North Cardinal St.
Dorchester Center, MA 02124

下面是一個完整、可實作的範例,示範如何用 Laravel(API)+ Vue 3(前端) 建立一個「短網址(Short URL)系統」。
後端用 Laravel 架構風格來寫(Controller + Migration),前端用 Vue 3 Composition API + Axios。
網址: https://twingo.polinwei.com/pages/ShortUrl

Frontend (Vue 3)
└─ 輸入長網址 → 呼叫 API → 顯示短網址
Backend (Laravel)
├─ POST /api/short-urls 建立短網址
├─ GET /{code} 轉址
└─ short_urls table
先建立後端 Laravel 必要程式
php artisan make:migration create_short_urls_table修改 table schema: short_urls
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');
}
};建立表格
php artisan migrateclass ShortUrl extends Model
{
// 指定資料表名稱
protected $table = 'short_urls';
// 可批量賦值的屬性
protected $fillable = [
'original_url',
'code',
'clicks',
'expired_at',
];
}建立控制器 ShortUrlController
php artisan make:controller Api/ShortUrlController程式碼內容
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,
]);
}
}建立轉址的控制器: RedirectController
php artisan make:controller RedirectController程式碼內容
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/api.php
Route::post('/short-urls', [\App\Http\Controllers\Api\ShortUrlController::class, 'store']);
// 檔案: routes/web.php
Route::get('/{code}', \App\Http\Controllers\RedirectController::class)
->where('code', '[A-Za-z0-9]+');
再來是前端畫面的呈現
// 檔案: src/api/shortUrl.js
import axios from 'axios'
export function createShortUrl(url) {
return axios.post('/api/short-urls', {
url,
})
}
// 檔案: 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,
}
}// 檔案: 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 呼叫
✔ 架構清楚、可擴充、可商用