您好,欢迎访问一九零五行业门户网

Model保留ID的情况下对外提供UUID

在某些应用程序中,不暴露 id 可以避免别人轻易获悉你数据库里模型的数量。
译者注:隐藏 id 也可有效防止用户恶意遍历网站的内容。
嘿, 想象一下,在我的 podcast 应用程序中,我设置了一个默认 id 在 laravel 的 podcast 模型中,它是一个整数,每次插入一行时都会自动增加一个,因此表中的第47个 podcast 的 id 为47。 然后我在我的网站内声称:“这个 podcast 应用程序拥有数百万个播客,所以千万不要错过!”,在看到最新播客 id 时很容易被揭穿:
https://podcast.app/podcasts/47
在不需要重新连接应用程序中的所有内容的情况下隐藏id,并且希望不被识破? 好的,有一种方法。
设置数据库有些数据库可以配置为在插入新行时将 uuid 设置为主键。你应该在正在使用的 rdbms 上检查这一点,因为每个 rdbms 的实现都有所不同。
你还可以告诉应用程序在使用 创建 eloqument 事件新纪录时设置默认 uuid ,但这将使你在任何情况下都得使用 eloqument 。如果你直接向数据库中插入一条记录,你可能会得到一个错误——这也是我喜欢在数据库中设置自动 uuid 而不是应用程序的原因之一,它不应该依赖于任何东西,因为这是数据库行为。
总之,你应该像这样使用 laravel 设置你的数据库:
<?phpuse illuminate\support\facades\schema;use illuminate\database\schema\blueprint;use illuminate\database\migrations\migration;class createpodcasttable extends migration{ /** * 运行数据库迁移 * * @return void */ public function up() { schema::create('podcast', function (blueprint $table) { $table->bigincrements('id');            $table->uuid('uuid')->index();            $table->string('filename');            $table->string('path');            $table->string('service');            $table->string('format', 4);            $table->unsginedtinyinteger('quality', 4);            $table->timestamps();            $table->timestamps();            $table->softdeletes();        });    }    /**     * 回滚数据库迁移     *     * @return void     */    public function down()    {        schema::dropifexists('podcast');    }}
正如你看到的,我们增加了 $table->uuid('uuid')->index() 。这段代码告诉 laravel 去使用 uuid 这一列(如果支持,或者使用字符串列),并在这一列上创建一个索引,这样就可以通过 uuid 快速检索行,就像有人访问这个 url 时所做的那样:
https://podcast.app/podcast/535c4cdf-70a0-4615-82f2-443e95c86aec
你可能会争辩说 另外一个索引会妨碍插入操作,但是这是一个权衡。
现在,问题在于控制器和模型。
将模型连接至 uuid你不需要在模型中做任何事,除了两件事:将 id 从序列化中隐藏,并允许模型使用 uuid 进行「 url 路由」。
<?phpnamespace app;use illuminate\database\eloquent\model;class podcast extends model{ /** * 数组中隐藏的属性 * * @var array */ protected $hidden = [ 'id' ]; /** * 获取模型的路由键 * * @return string */ public function getroutekeyname() { return 'uuid'; } // ……其余的模型代码}
要隐藏 id ,我们可以将 id 列添加至隐藏属性数组中。当模型被序列化时,比如转换为数组或 json 字符串时,将不会显示 id 。当然,你也可以像访问属性或者数组键那样访问获得的属性的 id。
下一步则告诉 laravel ,当 url 包含模型的 uuid 时,则通过 uuid 列获取模型。这将允许通过设置一个路由来查找模型,例如:
route::get({podcast}, 'podcastcontroller@show');
然后在我们的 podcastcontroller 类中使用它。
/** * 通过 uuid 显示播客 * * @param \app\podcast $podcast * @return \illuminate\http\response/* public function show(podcast $podcast){ return response()->view('response', [        'podcast' => $podcast    ]);}
你也可以使用模型中的 resolveroutebinding() 方法,你是否可以以编程的方式设置如何通过给定值来检索模型。你甚至可以允许经过身份验证的管理员根据记录的 id 或者 uuid 来获取记录。
就这样,没什么可做的了。该技术还允许在 应用程序生成后 设置 uuid 。
更多laravel相关技术文章,请访问laravel教程栏目进行学习!
以上就是model保留id的情况下对外提供uuid的详细内容。
其它类似信息

推荐信息