Generate id auto in Laravel with date

Generate id auto in Laravel with date

Generate ID auto in Laravel with date

Hello dear,

To generate an auto ID in Laravel that incorporates the current date, you can create a custom method in your model or a service class. Here’s how to do it using a model's boot method:


  
 

 
Prerequisites:

* Git: Git is a version control system used for tracking changes in source code during software development. Make sure Git is installed on your system. You can download Git from https://git-scm.com/ and follow the installation instructions for your operating system.

* PHP: Laravel requires PHP to be installed on your system. You need PHP version 7.3 or higher. You can check your PHP version by running php -v in your terminal.

* Composer: Composer is a dependency manager for PHP and is used to install Laravel and its dependencies. You can download Composer from https://getcomposer.org/ and follow the installation instructions for your operating system.

* Web Server: You'll need a web server to serve your Laravel application. While Laravel comes with a built-in development server, it's recommended that Apache or Nginx be used for production deployments.

* Database: If the cloned project uses a database, make sure you have the required database management system (e.g., MySQL, PostgreSQL, SQLite) installed on your system. 

app/Models/User.php

<?php

namespace App\Models;

// use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;

class User extends Authenticatable
{
    use HasFactory, Notifiable;

    /**
     * The attributes that are mass assignable.
     *
     * @var array<int, string>
     */

    protected $fillable = [
        'user_id',
        'name',
    ];

    /**
     * The attributes that should be hidden for serialization.
     *
     * @var array<int, string>
     */
    protected $hidden = [
        'password',
        'remember_token',
    ];

    /**
     * Get the attributes that should be cast.
     *
     * @return array<string, string>
     */
    protected function casts(): array
    {
        return [
            'email_verified_at' => 'datetime',
            'password' => 'hashed',
        ];
    }

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

        self::creating(function ($model) {
            // Get the latest record by created_at
            $latestID = self::latest('created_at')->first();

            // Get current year, month, and day
            $currentYear  = date('Y');
            $currentMonth = date('m');

            // Construct user ID prefix
            $userIdPrefix = 'KH-' . $currentYear . '-' . $currentMonth . '-';

            // Determine the next ID number
            if ($latestID && strpos($latestID->user_id, $userIdPrefix) === 0) {
                // Extract the latest ID number
                $latestIDNumber = intval(substr($latestID->user_id, -5));
                $nextIDNumber = $latestIDNumber + 1;
            } else {
                // Start with 1 if no records or different month/year
                $nextIDNumber = 1;
            }

            // Assign the new user ID to the model
            $model->user_id = $userIdPrefix . sprintf("%05s", $nextIDNumber);
        });
    }
}

Reactions

Post a Comment

0 Comments

close