master

laravel/framework

Last updated at: 29/12/2023 09:22

HasUniqueIds.php

TLDR

This file is a trait called HasUniqueIds that can be used in Laravel Eloquent models. It provides methods to manage unique ids for the model.

Methods

usesUniqueIds

This method returns a boolean indicating whether the model uses unique ids.

setUniqueIds

This method generates unique keys for the model by iterating over the columns returned by the uniqueIds method and setting their values if they are empty. It does nothing if the column already has a value.

newUniqueId

This method generates a new unique key for the model. However, in the provided code, it simply returns null. This method can be overridden in child classes to provide custom logic for generating unique ids.

uniqueIds

This method returns an empty array. Child classes can override this method to specify the columns that should receive unique identifiers.

<?php

namespace Illuminate\Database\Eloquent\Concerns;

trait HasUniqueIds
{
    /**
     * Indicates if the model uses unique ids.
     *
     * @var bool
     */
    public $usesUniqueIds = false;

    /**
     * Determine if the model uses unique ids.
     *
     * @return bool
     */
    public function usesUniqueIds()
    {
        return $this->usesUniqueIds;
    }

    /**
     * Generate unique keys for the model.
     *
     * @return void
     */
    public function setUniqueIds()
    {
        foreach ($this->uniqueIds() as $column) {
            if (empty($this->{$column})) {
                $this->{$column} = $this->newUniqueId();
            }
        }
    }

    /**
     * Generate a new key for the model.
     *
     * @return string
     */
    public function newUniqueId()
    {
        return null;
    }

    /**
     * Get the columns that should receive a unique identifier.
     *
     * @return array
     */
    public function uniqueIds()
    {
        return [];
    }
}