
Bug编译狮
好的,下面是一个使用 Laravel 和 Eloquent 设计简单 URL 短链接服务的示例。我们将创建一个 ShortLink 模型,并编写一些控制器来处理短链接的生成和解析。
1. 创建 ShortLink 模型
首先,创建一个新的模型文件 ShortLink.php 在 app/Models 目录下:
namespace AppModels;
use IlluminateDatabaseEloquentModel;
class ShortLink extends Model
{
protected $fillable = ['long_url'];
public function redirects()
{
return $this->hasMany(Redirect::class);
}
}
2. 创建 Redirect 模型
接下来,创建另一个模型文件 Redirect.php 在 app/Models 目录下:
namespace AppModels;
use IlluminateDatabaseEloquentModel;
class Redirect extends Model
{
protected $fillable = ['short_code', 'created_at'];
public function shortLink()
{
return $this->belongsTo(ShortLink::class);
}
}
3. 创建 ShortLinkController
现在,创建一个控制器文件 ShortLinkController.php 在 app/Http/Controllers 目录下:
namespace AppHttpControllers;
use AppModelsShortLink;
use AppModelsRedirect;
use IlluminateHttpRequest;
class ShortLinkController extends Controller
{
// 生成短链接
public function generate(Request $request)
{
$longUrl = $request->input('url');
if (empty($longUrl)) {
return response()->json(['error' => '请输入长URL'], 400);
}
$shortCode = str_random(6); // 生成随机短码
$redirect = new Redirect();
$redirect->short_code = $shortCode;
$redirect->short_link()->associate(new ShortLink());
$redirect->save();
return response()->json(['short_code' => $shortCode]);
}
// 解析短链接
public function parse(Request $request)
{
$shortCode = $request->input('code');
if (empty($shortCode)) {
return response()->json(['error' => '请输入短码'], 400);
}
$redirect = Redirect::where('short_code', $shortCode)->first();
if (!$redirect) {
return response()->json(['error' => '无效的短码'], 404);
}
$longUrl = $redirect->short_link()->long_url;
return redirect()->away($longUrl);
}
}
4. 配置路由
最后,配置路由文件 routes/web.php:
use AppHttpControllersShortLinkController;
Route::get('/generate', [ShortLinkController::class, 'generate']);
Route::get('/parse/{code}', [ShortLinkController::class, 'parse']);
示例代码
以下是一个完整的示例代码,展示了如何使用上述模型和控制器:
生成短链接
// 使用 POST 请求发送到 /generate 端点
$longUrl = 'https://example.com';
$response = file_get_contents('http://your-laravel-app.com/generate?url=' . urlencode($longUrl));
echo json_decode($response)->short_code; // 输出短码
解析短链接
// 使用 GET 请求发送到 /parse 端点
$shortCode = 'abc123'; // 替换为实际的短码
$response = file_get_contents('http://your-laravel-app.com/parse/' . $shortCode);
echo $response; // 输出重定向后的 URL
通过这些步骤,你可以创建一个简单的 URL 短链接服务。你可以根据需要扩展这个示例,例如添加更多的功能、优化性能等。

黑板Bug讲师
开始使用
URL短网址服务在社交媒体和在线营销的时代变得至关重要,它们简化了长URL,使它们更容易分享和管理。在这个教程中,我们将学习如何使用Laravel和Eloquent ORM构建一个基本的URL短网址服务。这包括设置数据库、创建模型以及定义路由。
创建一个新的Laravel项目:
composer create-project --prefer-dist laravel/laravel url-shortener
现在,请创建一个数据库并配置它。.env请提供文件以进行连接操作。
数据库和迁移
我们将首先创建一个迁移。shortened_urls对不起,我不明白你的意思。你需要我帮助翻译什么吗?
php artisan make:migration create_shortened_urls_table --create=shortened_urls
请提供需要编辑的迁移文件的具体路径或名称,以便我进行相应的修改和翻译。database/migrations添加文件夹并添加字段:
Schema::create('shortened_urls', function (Blueprint $table) {
$table->id();
$table->string('code')->unique();
$table->string('url');
$table->timestamps();
});
现在迁移数据库:
php artisan migrate
创建模型
创建Eloquent模型:
php artisan make:model ShortenedUrl
编辑ShortenedUrl模型:好的,请提供需要翻译的内容。
namespace AppModels;
use IlluminateDatabaseEloquentModel;
class ShortenedUrl extends Model
{
protected $fillable = ['url', 'code'];
}
处理URL短化逻辑
我们需要一个机制来为每个URL生成唯一的代码。以这个例子为例:
public static function boot()
{
parent::boot();
self::creating(function ($model) {
$model->code = substr(md5(uniqid(rand(), true)), 0, 6);
});
}
添加这个到你的ShortenedUrl模型。
路由和控制器
创建一个控制器来处理Web请求:
php artisan make:controller UrlShortenerController
编辑。UrlShortenerController:
namespace AppHttpControllers;
use IlluminateHttpRequest;
use AppModelsShortenedUrl;
class UrlShortenerController extends Controller
{
public function store(Request $request)
{
$request->validate(['url' => 'required|url']);
$shortenedUrl = ShortenedUrl::create(['url' => $request->url]);
return response()->json(['code' => $shortenedUrl->code], 201);
}
public function show($code)
{
$url = ShortenedUrl::where('code', $code)->firstOrFail();
return redirect($url->url);
}
}
定义路线:
use AppHttpControllersUrlShortenerController;
Route::post('/shorten', [UrlShortenerController::class, 'store']);
Route::get('/{code}', [UrlShortenerController::class, 'show']);
正在测试我们的服务,请稍候。
使用curl或者使用像Postman这样的HTTP客户端来测试您的服务:
curl -X POST -F 'url=https://www.google.com' http://localhost/shorten
收到,这是我的中文翻译:你会接收到一个包含您唯一代码的JSON响应,该代码会重定向到原始URL。
结论。
在本指南中,我们已经讨论了创建一个简单URL短化服务所需的步骤,使用Laravel和Eloquent。您的新服务涵盖了核心组件,例如迁移、模型、路由和控制器。虽然简单,但它为构建更复杂功能提供了基础,如分析、自定义别名或用户身份验证。
祝你编程愉快!

长工码奴1523
在 Laravel 和 Eloquent 中创建一个简单的 URL 短链接服务涉及到以下几个步骤:
- 安装 Laravel 首先,你需要在本地计算机上安装 Laravel。你可以使用 Composer 来安装它。
composer create-project --prefer-dist laravel/laravel url-shortener
- 创建数据库表 接下来,我们需要创建一个数据库表来存储我们的 URL 和其对应的短链接。这可以通过运行以下命令来完成:
php artisan make:model ShortLink
cd short-link
php artisan db:seed --class=ShortLinkSeeder
- 实现模型和控制器
现在我们有了数据库表,我们可以实现我们的模型和控制器。在
app/Models目录下,我们可以找到ShortLink.php文件。
<?php
namespace AppModels;
use IlluminateDatabaseEloquentModel;
use IlluminateDatabaseEloquentSoftDeletes;
class ShortLink extends Model
{
use SoftDeletes;
protected $fillable = [
'short_link',
'long_url'
];
public function getRouteKeyName()
{
return 'short_link';
}
}
然后,我们将实现控制器,例如 ShortLinkController.php。
<?php
namespace AppHttpControllers;
use AppModelsShortLink;
use IlluminateHttpRequest;
class ShortLinkController extends Controller
{
/**
* Display a listing of the resource.
*
* @return IlluminateHttpResponse
*/
public function index()
{
$shortLinks = ShortLink::all();
return view('short-links.index', compact('shortLinks'));
}
/**
* Show the form for creating a new resource.
*
* @return IlluminateHttpResponse
*/
public function create()
{
return view('short-links.create');
}
/**
* Store a newly created resource in storage.
*
* @param IlluminateHttpRequest $request
* @return IlluminateHttpResponse
*/
public function store(Request $request)
{
$request->validate([
'short_link' => ['required'],
'long_url' => ['required']
]);
ShortLink::create($request->only(['short_link', 'long_url']));
return redirect()->route('short-links.index')
->with('success', '短链接已成功添加!');
}
/**
* Display the specified resource.
*
* @param int $id
* @return IlluminateHttpResponse
*/
public function show($id)
{
//
}
/**
* Show the form for editing the specified resource.
*
* @param int $id
* @return IlluminateHttpResponse
*/
public function edit($id)
{
$shortLink = ShortLink::findOrFail($id);
return view('short-links.edit', compact('shortLink'));
}
/**
* Update the specified resource in storage.
*
* @param IlluminateHttpRequest $request
* @param int $id
* @return IlluminateHttpResponse
*/
public function update(Request $request, $id)
{
$request->validate([
'short_link' => ['required'],
'long_url' => ['required']
]);
ShortLink::whereId($id)->update($request->only(['short_link', 'long_url']));
return redirect()->route('short-links.index')
->with('success', '短链接已成功更新!');
}
/**
* Remove the specified resource from storage.
*
* @param int $id
* @return IlluminateHttpResponse
*/
public function destroy($id)
{
ShortLink::destroy($id);
return redirect()->route('short-links.index')
->with('success', '短链接已成功删除!');
}
}
- 配置路由 最后,我们需要配置路由以便在应用程序中访问这些资源。
php artisan route:编辑
现在,当用户尝试访问 /short-links 路径时,他们将看到一个显示所有短链接的页面。点击按钮将重定向到短链接的详细信息页面。点击“创建”按钮将向服务器提交一个 POST 请求,以添加一个新的短链接。点击“编辑”按钮将重定向到编辑短链接的页面。点击“删除”按钮将从数据库中删除指定的短链接。
以上就是使用 Laravel 和 Eloquent 实现简单 URL 短链接服务的基本过程。

