search
HomePHP FrameworkLaravelModel provides UUID to the outside world while retaining ID.

Model provides UUID to the outside world while retaining ID.

In some applications, not exposing the ID can prevent others from easily knowing the number of models in your database.

Translator’s Note: Hiding the ID can also effectively prevent users from maliciously traversing the content of the website.

Hey, Imagine that in my Podcast application, I set a default id. In Laravel's Podcast model, it is an integer that is automatically incremented by one every time a row is inserted, Therefore, the id of the 47th Podcast in the table is 47. I then claimed within my website: "This Podcast app has millions of podcasts, so don't miss out!", which was easily debunked when seeing the latest podcast ID:

https://podcast.app/podcasts/47

Hide the ID without rewiring everything in the app and hope not to be seen through? OK, there is a way.

Setting up the database

Some databases can be configured to set the UUID as the primary key when inserting new rows. You should check this on the RDBMS you are using, as each RDBMS implementation is different.

You can also tell the application to set the default UUID when creating new records using Eloqument events, but this will force you to use Eloqument in all cases. If you insert a record directly into the database you may get an error - this is one of the reasons why I prefer setting automatic UUIDs in the database rather than in the application, it shouldn't depend on anything as this is database behavior .

In summary, you should set up your database using Laravel like this:

<?php use 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(&#39;podcast&#39;, 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');
    }
}

As you can see, we added $table->uuid('uuid')- >index(). This code tells Laravel to use the UUID column (or use the string column if supported) and create an index on this column so that rows can be quickly retrieved by UUID, just like they would if someone visited this URL :

https://podcast.app/podcast/535c4cdf-70a0-4615-82f2-443e95c86aec

You could argue that another index would hinder insert operations, but that's a trade-off.

Now, the problem lies with the controller and the model.

Connecting models to UUIDs

You don’t need to do anything in the model except two things: hide the ID from serialization and allow the model to use the UUID for "URL routing" .

<?php namespace App;
use Illuminate\Database\Eloquent\Model;
class Podcast extends Model
{
    /**
     * 数组中隐藏的属性
     *
     * @var array
     */
    protected $hidden = [
        &#39;id&#39;
    ];

    /**
     * 获取模型的路由键
     *
     * @return string
     */
    public function getRouteKeyName()
    {
        return &#39;uuid&#39;;
    }

    // ……其余的模型代码
}

To hide the ID, we can add the id column to the hidden properties array. When the model is serialized, such as converted to an array or JSON string, the ID will not be displayed. Of course, you can also access the ID of the obtained property just like a property or array key.

The next step is to tell Laravel that when the URL contains the UUID of the model, get the model through the uuid column. This will allow the model to be looked up by setting up a route such as:

Route::get({podcast}, 'PodcastController@show');

and then using it within our PodcastController class.

/**
 * 通过 UUID 显示播客
 *
 * @param  \App\Podcast $podcast
 * @return \Illuminate\Http\Response
/* 
public function show(Podcast $podcast)
{
    return response()->view('response', [
        'podcast' => $podcast
    ]);
}

You can also use the resolveRouteBinding() method in the model if you can programmatically set how to retrieve the model by a given value. You can even allow authenticated administrators to retrieve records based on their ID or UUID.

That's it, there's nothing more to do. This technology also allows the UUID to be set after the application is built.

For more Laravel related technical articles, please visit the

Laravel Tutorial column to learn!

The above is the detailed content of Model provides UUID to the outside world while retaining ID.. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Laravel framework skills sharingLaravel framework skills sharingApr 18, 2025 pm 01:12 PM

In this era of continuous technological advancement, mastering advanced frameworks is crucial for modern programmers. This article will help you improve your development skills by sharing little-known techniques in the Laravel framework. Known for its elegant syntax and a wide range of features, this article will dig into its powerful features and provide practical tips and tricks to help you create efficient and maintainable web applications.

The difference between laravel and thinkphpThe difference between laravel and thinkphpApr 18, 2025 pm 01:09 PM

Laravel and ThinkPHP are both popular PHP frameworks and have their own advantages and disadvantages in development. This article will compare the two in depth, highlighting their architecture, features, and performance differences to help developers make informed choices based on their specific project needs.

Laravel user login function listLaravel user login function listApr 18, 2025 pm 01:06 PM

Building user login capabilities in Laravel is a crucial task and this article will provide a comprehensive overview covering every critical step from user registration to login verification. We will dive into the power of Laravel’s built-in verification capabilities and guide you through customizing and extending the login process to suit specific needs. By following these step-by-step instructions, you can create a secure and reliable login system that provides a seamless access experience for users of your Laravel application.

What versions of laravel are there? How to choose the version of laravel for beginnersWhat versions of laravel are there? How to choose the version of laravel for beginnersApr 18, 2025 pm 01:03 PM

In the Laravel framework version selection guide for beginners, this article dives into the version differences of Laravel, designed to assist beginners in making informed choices among many versions. We will focus on the key features of each release, compare their pros and cons, and provide useful advice to help beginners choose the most suitable version of Laravel based on their skill level and project requirements. For beginners, choosing a suitable version of Laravel is crucial because it can significantly impact their learning curve and overall development experience.

How to view the version number of laravel? How to view the version number of laravelHow to view the version number of laravel? How to view the version number of laravelApr 18, 2025 pm 01:00 PM

The Laravel framework has built-in methods to easily view its version number to meet the different needs of developers. This article will explore these methods, including using the Composer command line tool, accessing .env files, or obtaining version information through PHP code. These methods are essential for maintaining and managing versioning of Laravel applications.

The latest method of using php framework laravelThe latest method of using php framework laravelApr 18, 2025 pm 12:57 PM

Laravel is a popular PHP-based web application framework that is popular among developers for its elegant syntax and powerful features. Its latest version introduces many improvements and new features designed to improve the development experience and application performance. This article will dive into Laravel's latest approach, focusing on how to leverage these updates to build more powerful and efficient web applications.

Laravel framework installation methodLaravel framework installation methodApr 18, 2025 pm 12:54 PM

Article summary: This article provides detailed step-by-step instructions to guide readers on how to easily install the Laravel framework. Laravel is a powerful PHP framework that speeds up the development process of web applications. This tutorial covers the installation process from system requirements to configuring databases and setting up routing. By following these steps, readers can quickly and efficiently lay a solid foundation for their Laravel project.

How to learn Laravel How to learn Laravel for freeHow to learn Laravel How to learn Laravel for freeApr 18, 2025 pm 12:51 PM

Want to learn the Laravel framework, but suffer from no resources or economic pressure? This article provides you with free learning of Laravel, teaching you how to use resources such as online platforms, documents and community forums to lay a solid foundation for your PHP development journey from getting started to master.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
Will R.E.P.O. Have Crossplay?
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)