Usage scenario: Use the model to create a data, and the ID using uUID automatically take over;

Necessary knowledge: never learned PHP, nothing necessary;

Instead of building tables and models, get right to the point!

Models (Tabs)

use Ramsey\Uuid\Uuid;
use Illuminate\Support\Str;
class Tabs extends Model
{
    /** * Turn off automatic growth (ID) for the primary key *@var string
     */
    public $incrementing = false;
    /** * Configures the field to allow operations (automatic takeover ID, no need to configure here) *@var array
     */
    protected $fillable = ['title'];
    /** * The model's "booted" method (automatically takes over id when using model CREATE) *@return void
     */
    protected static function booted()
    {
        static::creating(function ($tabs) {
            if (! $tabs->getKey()) {
                $tabs- > {$tabs->getKeyName()} = (string) Uuid::uuid4()->getHex(); // Method 1: uUID plug-in library
                //$tabs->{$tabs->getKeyName()} = (string) Str::uuid();; // Method 2: Str comes with its own method}}); }}Copy the code

Controller (TabsController)

class TabsController extends Controller
{
     /** * Store a newly created resource in storage@param \Illuminate\Http\Request $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $data = $request->only([ 'title']);
        $res = Tabs::create($data);
        return response($res); }}Copy the code

Response (Mode 1)

{
    "title": "Test label 1"."id": "q8fdf2d0c38d8sfdbjfc2s743dfba2af"
}
Copy the code

Installing a plug-in

ramsey/uuid – github

composer require ramsey/uuid
Copy the code

That’s it! Call it a day! If you have anything to add, please discuss it in the comments section below.

  • LearnKu Community home page
  • Nuggets Community home page