首页 > 其他分享 >文章详情URL不使用ID用slug和uuiid代替

文章详情URL不使用ID用slug和uuiid代替

时间:2024-05-15 16:19:02浏览次数:14  
标签:function uuiid URL posts class post slug uuid

在 Laravel 中,可以通过使用 slugUUID 来展示文章详情和文章列表。这样可以提高 URL 的可读性和安全性。以下是实现方法和代码示例:

方法一:使用 Slug

数据库字段

首先,在 posts 表中添加 slug 字段:

Schema::table('posts', function (Blueprint $table) {
    $table->string('slug')->unique()->comment('文章的唯一别名');
});

模型设置

Post 模型中,确保 slug 字段可以被填充:

class Post extends Model
{
    protected $fillable = ['title', 'content', 'slug'];
    
    // 生成slug的方法
    public static function boot()
    {
        parent::boot();

        static::creating(function ($post) {
            $post->slug = Str::slug($post->title);
        });
    }

    // 这里你可以定义更多的方法和关系
}

控制器

在控制器中使用 slug 来查询文章详情:

class PostController extends Controller
{
    // 展示文章列表
    public function index()
    {
        $posts = Post::all();
        return view('posts.index', compact('posts'));
    }

    // 展示单篇文章详情
    public function show($slug)
    {
        $post = Post::where('slug', $slug)->firstOrFail();
        return view('posts.show', compact('post'));
    }
}

路由

在路由文件中定义使用 slug 的路由:

use Illuminate\Support\Facades\Route;

Route::get('/posts', [PostController::class, 'index'])->name('posts.index');
Route::get('/posts/{slug}', [PostController::class, 'show'])->name('posts.show');

方法二:使用 UUID

数据库字段

posts 表中添加 uuid 字段:

Schema::table('posts', function (Blueprint $table) {
    $table->uuid('uuid')->unique()->comment('文章的唯一标识符');
});

模型设置

Post 模型中,确保 uuid 字段可以被填充:

use Illuminate\Support\Str;

class Post extends Model
{
    protected $fillable = ['title', 'content', 'uuid'];

    // 生成UUID的方法
    public static function boot()
    {
        parent::boot();

        static::creating(function ($post) {
            $post->uuid = (string) Str::uuid();
        });
    }

    // 这里你可以定义更多的方法和关系
}

控制器

在控制器中使用 uuid 来查询文章详情:

class PostController extends Controller
{
    // 展示文章列表
    public function index()
    {
        $posts = Post::all();
        return view('posts.index', compact('posts'));
    }

    // 展示单篇文章详情
    public function show($uuid)
    {
        $post = Post::where('uuid', $uuid)->firstOrFail();
        return view('posts.show', compact('post'));
    }
}

路由

在路由文件中定义使用 uuid 的路由:

use Illuminate\Support\Facades\Route;

Route::get('/posts', [PostController::class, 'index'])->name('posts.index');
Route::get('/posts/{uuid}', [PostController::class, 'show'])->name('posts.show');

选择哪种方法

  • Slug:适用于 SEO 友好的 URL,适合公开展示的文章或内容。
  • UUID:适用于需要唯一标识和防止暴力破解的情况,适合保密性要求高的内容。

完整示例

以下是一个完整的示例,展示如何使用 slug

迁移文件

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class AddSlugToPostsTable extends Migration
{
    public function up()
    {
        Schema::table('posts', function (Blueprint $table) {
            $table->string('slug')->unique()->comment('文章的唯一别名');
        });
    }

    public function down()
    {
        Schema::table('posts', function (Blueprint $table) {
            $table->dropColumn('slug');
        });
    }
}

Post 模型

use Illuminate\Support\Str;
use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
    protected $fillable = ['title', 'content', 'slug'];

    protected static function boot()
    {
        parent::boot();

        static::creating(function ($post) {
            $post->slug = Str::slug($post->title);
        });
    }
}

PostController 控制器

use App\Models\Post;
use Illuminate\Http\Request;

class PostController extends Controller
{
    public function index()
    {
        $posts = Post::all();
        return view('posts.index', compact('posts'));
    }

    public function show($slug)
    {
        $post = Post::where('slug', $slug)->firstOrFail();
        return view('posts.show', compact('post'));
    }
}

路由文件

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\PostController;

Route::get('/posts', [PostController::class, 'index'])->name('posts.index');
Route::get('/posts/{slug}', [PostController::class, 'show'])->name('posts.show');

这样,你就可以通过 slugUUID 来展示文章列表和文章详情了。选择合适的方法取决于你的具体需求和项目要求。

标签:function,uuiid,URL,posts,class,post,slug,uuid
From: https://www.cnblogs.com/laraveler/p/18194116

相关文章

  • 用javax.ws.rs.client.Invocation queryParam 执行url中带参数的请求
    来自于百度AI,为了实际需要,改成我自己的环境。importlombok.AllArgsConstructor;importlombok.Data;importlombok.NoArgsConstructor;importorg.apache.commons.lang3.StringUtils;importorg.glassfish.jersey.client.ClientConfig;importorg.glassfish.jersey.client......
  • Python 常用第三方库 urllib3使用
    urllib3概述线程安全连接池管理客户端SSL/TLS验证支持HTTP和SOCKS代理官方文档:urllib32.0.4documentationurllib3安装通过pip安装pipinstallurllib3urllib3发送HTTP请求导入urllib3模块创建PoolManager实例调用request()方法importur......
  • Linux 使用 curl 发送请求
    前言请各大网友尊重本人原创知识分享,谨记本人博客:南国以南i、提示:以下是本篇文章正文内容,下面案例可供参考#get请求json入参curlhttp://xxx.xxx:60512/scrm/chat/msg/selectFullChatListForDay-d'{"key":"215EACF20778586C788FFD9187AB0F72","qrDay":"2023-04-25"}�......
  • [996] Upload a file to an Amazon S3 bucket and obtain the URL of it using Python
    Certainly!TouploadafiletoanAmazonS3bucketusingPython(specificallywiththeboto3library)andobtainthelink(URL)forthatfile,followthesesteps:InstallBoto3:Makesureyouhavetheboto3libraryinstalled.Ifnot,youcaninstallit......
  • prometheus+grafana 使用blackbox_exporte监控站点url
    1.1下载blackbox_exporte插件在https://github.com/prometheus/blackbox_exporter 上下载blackbox_exporte对应版本安装包,并上传到prometheus服务器 /usr/local 目录1.2安装blackbox_exporte[root@rancherlocal]#tarxvfblackbox_exporter-0.25.0.linux-amd64.tar.g......
  • 用curl调试简单webapi
    curl,即用户url。windows自带(据说新版的linux也自带),可以发送请求,用来简单调试webapi很合适。使用:cmd下直接输入命令。 例子:对于模型类 publicrecordStu(stringXm,intNl); post表单:curl-XPOST-d"Xm=ZS&Nl=20"http://localhost:5205/weatherforecast接收的weba......
  • GRPC - grpcurl: interact with gRPC servers
    https://github.com/fullstorydev/grpcurl Install:goinstallgithub.com/fullstorydev/grpcurl/cmd/grpcurl@latest Addcodetoenableserverreflection:import"google.golang.org/grpc/reflection"reflection.Register(s)//sisagrpcserver......
  • 不安全的URL跳转(Pikachu)
    原理URL跳转漏洞学习-FreeBuf网络安全行业门户修复1.若跳转的URL事先是可以确定的,包括url和参数的值,则可以在后台先配置好,url参数只需传对应url的索引即可,通过索引找到对应具体url再进行跳转;2.若跳转的URL事先不确定,但其输入是由后台生成的(不是用户通过参数传人),则可以先生成......
  • linux环境静态编译openssl、curl
    编译opensslopenssl下载地址:https://www.openssl.org/source/index.htmltarzxvfopenssl-3.3.0.tar.gzcdopenssl-3.3.0/./config-fPICno-shared--prefix=/root/openssl_install--openssldir=/root/openssl_installmakemakeinstall编译curlcurl下载地址:https:/......
  • curl 的用法指南
    简介curl是常用的命令行工具,用来请求Web服务器。它的名字就是客户端(client)的URL工具的意思。它的功能非常强大,命令行参数多达几十种。如果熟练的话,完全可以取代Postman这一类的图形界面工具。本文介绍它的主要命令行参数,作为日常的参考,方便查阅。内容主要翻译自《curl......